Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 646
Marian Avatar asked Dec 27 '17 16:12

Marian


People also ask

How do you concatenate elements in a list in Java?

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.

What is the easiest way to concatenate strings in Java 8?

In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.

How do you combine a list of strings in Java?

In Java, we can use String. join(",", list) to join a List String with commas.

Can you concatenate lists in Java?

Concatenating two lists means merging two lists into a single list. There are several methods to perform concatenation operation: Using addAll() method.


1 Answers

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.

like image 177
Szymon Stepniak Avatar answered Oct 20 '22 21:10

Szymon Stepniak