Display a list of strings in Java 8 format

I have a list of such objects:

[ {value: 1, tag: a}, {value: 2, tag: a}, {value: 3, tag: b}, {value: 4, tag: b}, {value: 5, tag: c}, ] 

where each of its objects is an instance of the Entry class, which has tag and value as properties. I want to group them as follows:

 { a: [1, 2], b: [3, 4], c: [5], } 

This is what I have 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 need a list of strings as the values ​​of my new mapping ( Map<String, List<String>> ), and not a list of objects ( Map<String, List<Entry>> ). How can I achieve this using Java 8 with new cool features?

+5
source share
1 answer

Use mapping :

 Map<String, List<String>> map = entries.stream() .collect(Collectors.groupingBy(Entry::getTag, Collectors.mapping(Entry::getValue, toList()))); 
+9
source

Source: https://habr.com/ru/post/1215232/


All Articles