java - 如何使用 Java 8 和 StringJoiner 连接列表中的两个字段?

标签 java string java-8

我有课:

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/

相关文章:

java - 如何在数组列表中打印字符串值而不打印空值?

javascript - 如何使用javascript从字符串末尾删除多个逗号?

java - 将 foreach 转换为 lambda 表达式

java - summarizingInt 和 Collectors.summarizingInt 之间的区别?

python - 将字符串拆分为python中的列表

java - 如何使用多线程并行化 Java 中的 for 循环?

linux 上的 java unicode 转换不适用于 mac os x

javascript - 如何用Java触发js事件?

java - 使用 animateLayoutChanges 调整 EditText 大小时光标位于错误位置

python - 为什么变量1 + =变量2要比变量1 =变量1 +变量2快得多?