How to convert a set to a list in Java?

One way to convert a Set into a List is by using the constructor of ArrayList, as shown below:

import java.util.*;

public class SetToList {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("A");
        set.add("B");
        set.add("C");

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

        System.out.println("Set elements: " + set);
        System.out.println("List elements: " + list);
    }
}

In the example above, we first create a Set and add elements to it, then convert the Set to a List using the constructor of ArrayList, and finally output the elements in the Set and List.

bannerAds