The first step is to join field1 and field2 .
The second step is to join ; .
Please note that this will not add ; In the end.
List<Item> items = asList(new Item("One", "Two"), new Item("Three", "Four")); String joined = items.stream() // First step .map(it -> it.field1 + ": " + it.field2) // Second step .collect(Collectors.joining("; "));
Somewhat more OO
Or even better: move the logic to join field1 and field2 to the highlighted 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 it in a stream.
String joined = items.stream() .map(Item::getField1And2) .collect(Collectors.joining("; "));
source share