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.
String concatenation using Collectors.joining() method (Java (Java Version 8+) The Collectors class in Java 8 offers joining() method that concatenates the input elements in a similar order as they occur. Here, a list of String array is declared. And a String object str stores the result of Collectors.joining() method.
In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.
In Java, we can use String. join(",", list) to join a List String with commas.
Concatenating two lists means merging two lists into a single list. There are several methods to perform concatenation operation: Using addAll() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With