Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 353
Oneiros Avatar asked Mar 12 '15 14:03

Oneiros


1 Answers

Use mapping:

Map<String, List<String>> map = 
  entries.stream()
         .collect(Collectors.groupingBy(Entry::getTag, 
                                        Collectors.mapping(Entry::getValue, toList())));
like image 85
Eran Avatar answered Sep 19 '22 21:09

Eran