Java 8 stream, converting object list to map >
I've experienced some examples that don't work for me
This is what I want to do:
I have a list < someclass > of the following courses:
class SomeClass { String rid; String name; ... }
The values in my list are as follows:
SomeClass(1,"apple") SomeClass(1,"banana") SomeClass(1,"orange") SomeClass(2,"papaya") SomeClass(2,"peaches") SomeClass(3,"melons")
I want to convert the above list into map < string, set < string > >, where key is rid and value is set of name field
To use Java streams to solve this problem, I am using groupingby. I can use the following solutions:
someClassList .stream() .map(SomeClass::getName) .collect( Collectors.groupingBy( SomeClass::getRid,Collectors.toSet()));
But this gave me a compilation error How do I solve this problem and what's wrong with my method?
Solution
When you call on stream < someclass > Map (someclass:: getname), you will get a stream < string > You cannot execute collect (collectors. Groupingby (someclass:: getrid,...)) on stream < string > (you can only execute it on stream < someclass >)
You need to add collectors The collector returned by mapping () is passed to collectors Groupingby() to map someclass instances to strings after grouping them by getrid
Map<String,Set<String>> map = someClassList.stream() .collect(Collectors.groupingBy(SomeClass::getRid,Collectors.mapping(SomeClass::getName,Collectors.toSet())));