I have a list of objects like this:
[
{value: 1, tag: a},
{value: 2, tag: a},
{value: 3, tag: b},
{value: 4, tag: b},
{value: 5, tag: c},
]
where every object of it is an instance of a class Entry
, which has tag
and value
as properties. I want to group them in this way:
{
a: [1, 2],
b: [3, 4],
c: [5],
}
This is what I've done so far:
List<Entry> entries = <read from a file>
Map<String, List<Entry>> map = entries.stream()
.collect(Collectors.groupingBy(Entry::getTag, LinkedHashMap::new, toList()));
And this is my result (not what i wanted):
{
a: [{value: 1, tag: a}, {value: 2, tag: a}],
b: [{value: 3, tag: b}, {value: 4, tag: b}],
c: [{value: 5, tag: c}],
}
In other words, I want a list of strings as values of my new mapping (Map<String, List<String>>
), and not a list of objects (Map<String, List<Entry>>
).
How can I achieve this with Java 8 new cool features?
Use mapping
:
Map<String, List<String>> map =
entries.stream()
.collect(Collectors.groupingBy(Entry::getTag,
Collectors.mapping(Entry::getValue, 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