How can I concatenate two fields from a list using Java 8 and StringJoiner?

java string java-8

328 观看


35 作者的声誉

I have class:

public class Item {

   private String first;
   private String second;

   public Item(String first, String second) {
       this.first = first;
       this.second = second;

And list of such objects:

List<Item> items = asList(new Item("One", "Two"), new Item("Three", "Four"));

My goal is to join list of elements in order to build following string:

One: Two; Three: Four;

I've tried to use StringJoiner, but it looks like it is designed to work with list of some simple types.

作者: Marian 的来源 发布者: 2017 年 12 月 27 日

回应 (3)


262019 作者的声誉

You can map the item to a string that concatenates the fields and then join the items, separating them with a space:

String result =
                     .map(it -> it.field1 + ": " + it.field2 + ";")
                     .collect(Collectors.joining(" "));
作者: assylias 发布者: 27.12.2017 05:01


21621 作者的声誉


You can try something like that:

final String result =
        .map(item -> String.format("%s: %s", item.first, item.second))
        .collect(Collectors.joining("; "));

As assylias mentioned in the comment below, last ; will be missed using this construction. It can be added manually to the final String or you can simply try solution suggested by assylias.

作者: Szymon Stepniak 发布者: 27.12.2017 05:02


1719 作者的声誉

First step is to join field1 and field2.

Second step is to join with ;.

Note that this won't add a ; at the end.

List<Item> items = asList(new Item("One", "Two"), new Item("Three", "Four"));

String joined =
        // First step
        .map(it -> it.field1 + ": " + it.field2)
        // Second step
        .collect(Collectors.joining("; "));

Somewhat more OO

Or better yet: move logic to join field1 and field2 to a dedicated method:

public static class Item {
    private String field1;
    private String field2;

    public Item(String field1, String field2) {
        this.field1 = field1;
        this.field2 = field2;

    public String getField1And2() {
        return field1 + ": " + field2;


And use that one in the stream.

String joined =
        .collect(Collectors.joining("; "));
作者: Ward 发布者: 27.12.2017 05:02