I have following class:
public class Foo {
private String areaName;
private String objectName;
private String lineName;
}
Now I want to convert a List<Foo>
to Map<String, Map<String, List<String>>>
. I found this answer which helped me develop following code:
Map<String, Map<String, List<String>>> testMap = foos.stream().collect(Collectors.groupingBy(e -> e.getAreaName(),
Collectors.groupingBy(e -> e.getObjectName(), Collectors.collectingAndThen(Collectors.toList(),
e -> e.stream().map(f -> f.getLineName())))));
The only problem with this code is the part where it should convert to List<String>
. I couldn't find a way to convert Foo
to List
in that part.
Another approach which results in Map<String, Map<String, List<Foo>>>
:
Map<Object, Map<Object, List<Foo>>> testMap = ventures.stream().collect(Collectors.groupingBy(e -> e.getAreaName(),
Collectors.groupingBy(e -> e.getObjectName(), Collectors.toList())));
What do I need to change in order to receive Map<String, Map<String, List<String>>>
from List<Foo>
?
In order to get a List
of a different type than the type of the Stream
elements, you should chain a Collectors.mapping
collector to groupingBy
:
Map<String, Map<String, List<String>>> testMap =
foos.stream()
.collect(Collectors.groupingBy(Foo::getAreaName,
Collectors.groupingBy(Foo::getObjectName,
Collectors.mapping(Foo::getLineName,
Collectors.toList()))));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With