作者:花长好月常圆人长久 | 来源:互联网 | 2022-12-10 14:22
如何解决《Java8streams,convertListofobjecttoMap<String,Set<String>>》经验,为你挑选了1个好方法。
I have already gone through few examples and those did not work for me.
Here is what I am trying to do:
I have a List
of the following class:
class SomeClass {
String rid;
String name;
...
}
The values in my List
look like this:
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 a Map>
, where key is rid
and value is Set
of name
field.
To solve this using Java Streams
I am using groupingBy
and I could come to below solution:
someClassList
.stream()
.map(SomeClass::getName)
.collect(
Collectors.groupingBy(
SomeClass::getRid, Collectors.toSet()));
But this gives me compilation error.
How do I solve this and what is the problem with my approach?
1> Eran..:
When you call .map(SomeClass::getName)
on your Stream
, you get a Stream
. You can't execute collect(Collectors.groupingBy(SomeClass::getRid,...))
on a Stream
(you can only execute it on a Stream
).
Therefore your map
step is wrong.
You need to pass the Collector
returned by Collectors.mapping()
to Collectors.groupingBy()
in order to map the SomeClass
instances to String
s after they are grouped by getRid
.
Map> map =
someClassList.stream()
.collect(Collectors.groupingBy(SomeClass::getRid,
Collectors.mapping(SomeClass::getName,
Collectors.toSet())));