Java 8 中有很多有用的新东西。例如,我可以用流遍历对象列表,然后对 Object
的实例的特定字段的值求和。例如
public class AClass {
private int value;
public int getValue() { return value; }
}
Integer sum = list.stream().mapToInt(AClass::getValue).sum();
因此,我想问是否有任何方法可以构建一个 String
将来自实例的 toString()
方法的输出连接在一行中。
List<Integer> list = ...
String concatenated = list.stream().... //concatenate here with toString() method from java.lang.Integer class
Suppose that list
contains integers 1
, 2
and 3
, I expect that concatenated
is "123"
或 "1,2,3"
。
原文由 mat_boy 发布,翻译遵循 CC BY-SA 4.0 许可协议
一种简单的方法是将列表项附加到
StringBuilder
你也可以尝试:
说明:map 将 Integer 流转换为 String 流,然后将其缩减为所有元素的串联。
注意:这是
normal reduction
在 O(n 2 ) 中执行为了获得更好的性能,请使用
StringBuilder
或mutable reduction
类似于 F. Böller 的回答。参考: 流减少