4

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]]
         }
    }

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

4

A way without streams:

List<List<Integer>> listOfLists = new ArrayList<>(map.size());
map.values().forEach(set -> listOfLists.add(new ArrayList<>(set)));

Comments

3

map from Set<String> to ArrayList<String> then collect to a list:

List<List<Integer>> result = map.values() // Collection<Set<String>>
                                .stream() // Stream<Set<String>>
                                .map(ArrayList::new) // Stream<ArrayList<String>>
                                .collect(toList()); // List<List<String>>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.