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())));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>