简体   繁体   中英

Java 8 Collector with string concatenating

I have this class:

class Pair {
    public String name;
    public int age;
}

And a list:

List<Pair> list = new LinkedList<>();
list.add(new Pair("One", 25));
list.add(new Pair("Two", 18));
list.add(new Pair("Three", 18));
list.add(new Pair("Four", 10));

Where Pair just contains two values, a String and an int .

I want to group this data by its age value, but also concatenate the name . In final I want to obtain a Map<Integer, String> like this:

25 - One
18 - TwoThree
10 - Four

I tried this :

list.stream().collect(Collectors.groupingBy(Pair::getValue, /* Collectors.??? */));

There are methods like summingInt , but can't find anything for String values.

I see there's a Collectors.reducing method, I'm guessing maybe we can use it, not sure how to though.

Is there an elegant way to do it with build in Collectors or I have to make my own ?

Just use Collectors.mapping(Pair::getName, Collectors.joining()) . joining deals with the strings, and mapping extracts them from the pair objects.

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