我有课:
public class Item {
private String first;
private String second;
public Item(String first, String second) {
this.first = first;
this.second = second;
}
}
以及此类对象的列表:
List<Item> items = asList(new Item("One", "Two"), new Item("Three", "Four"));
我的目标是加入元素列表以构建以下字符串:
One: Two; Three: Four;
我试过使用 StringJoiner,但看起来它是为处理一些简单类型的列表而设计的。
最佳答案
你可以尝试这样的事情:
final String result = items.stream()
.map(item -> String.format("%s: %s", item.first, item.second))
.collect(Collectors.joining("; "));
作为assylias在下面的评论中提到,最后一个 ;
使用此结构将被遗漏。它可以手动添加到最终的字符串中,或者您可以简单地尝试 assylias 建议的解决方案。
关于java - 如何使用 Java 8 和 StringJoiner 连接列表中的两个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47995882/