Bartosz Czy┼╝owski Bartosz Czy┼╝owski - 15 days ago 7
Java Question

List to Map - Collectors.toMap()

I have a

List<String> abc
collection. I need to convert it into
Map<String, TreeSet<String>
where the key is the sorted string from
abc
and this string before sorting is added to the TreeSet.
It is possible using
Collectors.toMap()
?

ex. pseudocode:
List<String> abc = ["ala","laa","qwe"]


Map<String, TreeSet<String> = {key = "aal" , values in treeset = "ala" , "laa"
key = "eqw" values in treeset = "qwe"}

Answer

groupingBy is the appropriate collector

Map<String, TreeSet<String>> map =    
    list.stream().collect(Collectors.groupingBy(
        s -> withSortedChars(s),
        Collectors.toCollection(TreeSet::new)));