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

zak zak :

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 java.util.stream.*;
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]]
         }
    }
Eugene :
 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()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72140&siteId=1