Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]]
         }
    }
like image 977
xmen-5 Avatar asked Dec 10 '22 04:12

xmen-5


2 Answers

 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()

like image 189
Eugene Avatar answered Dec 21 '22 22:12

Eugene


A way without streams:

List<List<Integer>> listOfLists = new ArrayList<>(map.size());
map.values().forEach(set -> listOfLists.add(new ArrayList<>(set)));
like image 31
fps Avatar answered Dec 21 '22 22:12

fps