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

I have a class:

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

And a list of such objects:

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

My goal is to put together a list of elements to build the following line:

 One: Two; Three: Four; 

I tried using StringJoiner, but it looks like it is designed to work with a list of some simple types.

+5
source share
3 answers

You can try something like this:

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

Like the assylias mentioned in the comment below, the latter ; will be skipped using this construct. It can be added manually to the final line or you can just try the solution suggested by assylias.

+9
source

You can map an element to a string that combines the fields and then appends to the elements, separating them with a space:

 String result = items.stream() .map(it -> it.field1 + ": " + it.field2 + ";") .collect(Collectors.joining(" ")); 
+10
source

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("; ")); 
+2
source

Source: https://habr.com/ru/post/1274353/


All Articles