Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set of String with Stream to HashMap in Java 8

How do I create HashMap of String and List of String out of Set of String with Stream?

Set<String> mySet;
Map<String, List<String>> = mySet.stream().map(string -> {
   // string will be my key
   // I have here codes that return List<String>
   // what to return here?
}).collect(Collectors.toMap(.....)); // what codes needed here?

Thank you.

like image 682
Julez Avatar asked Jul 11 '18 12:07

Julez


1 Answers

You don't need the map() step. The logic that produces a List<String> from a String should be passed to Collectors.toMap():

Map<String, List<String>> map = 
    mySet.stream()
         .collect(Collectors.toMap(Function.identity(),
                                   string -> {
                                       // put logic that returns List<String> here
                                   }));
like image 157
Eran Avatar answered Oct 02 '22 23:10

Eran