convert a Collection of Set<Integer> to a list of lists

  • A+

I have a HashMap<Integer, Set<Integer>>.

I want to convert the Collection of set in the map to a list of list.

For example:

import java.util.*; import*; public class Example {           public static void main( String[] args ) {              Map<Integer,Set<Integer>> map = new HashMap<>();              Set<Integer> set1 = Stream.of(1,2,3).collect(Collectors.toSet());              Set<Integer> set2 = Stream.of(1,2).collect(Collectors.toSet());              map.put(1,set1);              map.put(2,set2);               //I tried to get the collection as a first step              Collection<Set<Integer>> collectionOfSets = map.values();               // I neeed  List<List<Integer>> list = ......                //so the list should contains[[1,2,3],[1,2]]          }     } 


 map.values()     .stream()     .map(ArrayList::new)     .collect(Collectors.toList()); 

Your start was good: going for map.values() to begin with. Now, if you stream that, each element in the Stream is going to be a Collection<Integer> (each separate value that is); and you want to transform that each value to a List. In this case I have provided an ArrayList which has a constructor that accepts a Collection, thus the ArrayList::new method reference usage. And finally all those each individual values (once transformed to a List) are collected to a new List via Collectors.toList()


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: