What is the method to convert a Java set to a list?

To convert a Set to a List, you can use the List constructor method or the addAll() method.

  1. Constructing a list using the List constructor.
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);

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

In the code above, we created a Set and added elements to it. Then we used the constructor of List to convert the Set into a List.

  1. Utilize the addAll() method:
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);

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

In the above code, we created a Set and added elements to it. Then we created an empty List and used the addAll() method to add the elements from the Set to the List.

No matter which method is used, a list containing the elements of the Set will ultimately be obtained.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds