[英]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
. 其中Pair
仅包含两个值,即String
和int
。
I want to group this data by its age
value, but also concatenate the name
. 我想按age
值对这些数据进行分组,还要将name
连接起来。 In final I want to obtain a Map<Integer, String>
like this: 最后,我想获得一个Map<Integer, String>
像这样:
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. 有类似summingInt
方法,但找不到String
值的任何东西。
I see there's a Collectors.reducing
method, I'm guessing maybe we can use it, not sure how to though. 我看到有一个Collectors.reducing
方法,我想也许我们可以使用它,但不确定如何使用。
Is there an elegant way to do it with build in Collectors
or I have to make my own ? 是否有一种优雅的方法可以在Collectors
进行构建,还是我必须自己制作?
Just use Collectors.mapping(Pair::getName, Collectors.joining())
. 只需使用Collectors.mapping(Pair::getName, Collectors.joining())
。 joining
deals with the strings, and mapping
extracts them from the pair objects. joining
处理字符串,然后mapping
从对对象中提取它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.