Java streams: grouping lists into maps
•
Java
How do I use Java streams to do the following?
Suppose I have the following classes:
class Foo { Bar b; } class Bar { String id; String date; }
I have a list < foo > and I want to convert it to map < foo b.id,Map< Foo. b.date,Foo> ;. 1. E: first by foo b. ID combination, and then by foo b. Date combination I'm trying to use the following two steps, but the second one doesn't even compile:
Map<String,List<Foo>> groupById = myList .stream() .collect( Collectors.groupingBy( foo -> foo.getBar().getId() ) ); Map<String,Map<String,Foo>> output = groupById.entrySet() .stream() .map( entry -> entry.getKey(),entry -> entry.getValue() .stream() .collect( Collectors.groupingBy( bar -> bar.getDate() ) ) );
Thank you in advance
Solution
You can group your data at once, assuming that there are only different foos:
Map<String,Foo>> map = list.stream() .collect(Collectors.groupingBy(f -> f.b.id,Collectors.toMap(f -> f.b.date,Function.identity())));
Save some characters using static import:
Map<String,Foo>> map = list.stream() .collect(groupingBy(f -> f.b.id,toMap(f -> f.b.date,identity())));
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
二维码