使用流将对象列表转换为从 toString 方法获得的字符串 [英] Using streams to convert a list of objects into a string obtained from the toString method
问题描述
Java 8 中有很多有用的新东西.例如,我可以用流迭代对象列表,然后对来自 Object
实例的特定字段的值求和.例如
There are a lot of useful new things in Java 8. E.g., I can iterate with a stream over a list of objects and then sum the values from a specific field of the Object
's instances. E.g.
public class AClass {
private int value;
public int getValue() { return value; }
}
Integer sum = list.stream().mapToInt(AClass::getValue).sum();
因此,我在问是否有任何方法可以构建一个 String
,将 toString()
方法的输出从实例连接到一行中.
Thus, I'm asking if there is any way to build a String
that concatenates the output of the toString()
method from the instances in a single line.
List<Integer> list = ...
String concatenated = list.stream().... //concatenate here with toString() method from java.lang.Integer class
假设 list
包含整数 1
、2
和 3
,我希望 concatenated
是 "123"
或 "1,2,3"
.
Suppose that list
contains integers 1
, 2
and 3
, I expect that concatenated
is "123"
or "1,2,3"
.
推荐答案
一种简单的方法是将列表项附加到 StringBuilder
One simple way is to append your list items in a StringBuilder
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
StringBuilder b = new StringBuilder();
list.forEach(b::append);
System.out.println(b);
你也可以试试:
String s = list.stream().map(e -> e.toString()).reduce("", String::concat);
说明:map 将整数流转换为字符串流,然后将其缩减为所有元素的串联.
Explanation: map converts Integer stream to String stream, then its reduced as concatenation of all the elements.
注意:这是在 O(n2)
Note: This is normal reduction
which performs in O(n2)
为了获得更好的性能,请使用类似于 F. Böller 的答案的 StringBuilder
或 mutable reduction
.
for better performance use a StringBuilder
or mutable reduction
similar to F. Böller's answer.
String s = list.stream().map(Object::toString).collect(Collectors.joining(","));
参考:流减少
这篇关于使用流将对象列表转换为从 toString 方法获得的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!