How to convert a Java set to a list collection?

To convert a Java Set collection to a List collection, you can achieve this by using the List constructor method or the addAll method.

Option 1: Utilize the constructor method of List.

Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);

List<Integer> list = new ArrayList<>(set);

Option 2: Utilize the addAll method of the List.

Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);

List<Integer> list = new ArrayList<>();
list.addAll(set);

Both methods can convert a Set collection to a List collection while maintaining the original order of elements.

Leave a Reply 0

Your email address will not be published. Required fields are marked *