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

Marian :

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.

Szymon Stepniak :

You can try something like that:

final String result = items.stream()
        .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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=470225&siteId=1