Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Set of Set to List of List in Java

List<List<Integer>> lst = new ArrayList<List<>>();

Suppose I have list of list declared above with name as lst and I have a set of set elements variable declared below. How can I put elements of this set into lst?

Set<Set<Integer>> set = new HashSet<Set<>>();
like image 728
Aditya Avatar asked Aug 12 '21 13:08

Aditya


2 Answers

Let's say you have a set of sets:

Set<Set<Integer>> setOfSets = new HashSet<>();

To convert it into list of lists:

List<List<Integer>> listOfLists = new ArrayList<>();

Do the following:

for (Set<Integer> set : setOfSets) {
    listOfLists.add(new ArrayList<>(set));
}

When you pass any collection to the ArrayList constructor, it creates a new ArrayList with all elements from this collection. In other words, new ArrayList(set) is similar to list = new ArrayList() and then list.addAll(set).

like image 194
Vadik Avatar answered Oct 08 '22 11:10

Vadik


Use Java 8 features:

Set<Set<Integer>> data = new HashSet<>();

List<List<Integer>> result = data.stream()
                                 .map(ArrayList::new)
                                 .collect(Collectors.toList());

Example:

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

Set<Integer> set2 = new HashSet<>();
set2.add(4);
set2.add(5);
set2.add(6);

data.add(set1);
data.add(set2);

List<List<Integer>> result = data.stream()
                                 .map(ArrayList::new)
                                 .collect(Collectors.toList());

printing result:

[[1, 2, 3], [4, 5, 6]] // list of lists
like image 32
C.P.O Avatar answered Oct 08 '22 10:10

C.P.O