简体   繁体   中英

Java 8 mapping of list stream

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())));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM