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<>>();
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)
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With