使用Java 8将对象列表转换为从toString()方法获取的字符串 [英] Using Java 8 to convert a list of objects into a string obtained from the toString() method

查看:2944
本文介绍了使用Java 8将对象列表转换为从toString()方法获取的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();

因此,我问是否有办法构建字符串用于连接单行中实例的 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 ,我希望连接1231,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将整数流转换为String流,然后将其缩小为所有元素的串联。

Explanation: map converts Integer stream to String stream, then its reduced as concatenation of all the elements.

注意:这是正常减少,它在O(n 2 )中执行

Note: This is normal reduction which performs in O(n2)

为了获得更好的性能,使用 StringBuilder 可变减少类似于F.Böller的回答。

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(","));

参考: Stream Stream

这篇关于使用Java 8将对象列表转换为从toString()方法获取的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆