Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to join a list into a string

Short answer

For a list of strings use String.join():

void main() {
    var cities = List.of("Berlin", "Paris", "Rome");
    IO.println(String.join(", ", cities));
}

Output:

Berlin, Paris, Rome

Numbers and objects

Turn the elements into strings with map() and collect them with Collectors.joining():

record Product(String name, double price) {}
 
void main() {
    var cart = List.of(new Product("Tea", 3.5), new Product("Cake", 12.0));
 
    String text = cart.stream()
            .map(p -> p.name() + " " + p.price() + " €")
            .collect(Collectors.joining("; "));
    IO.println(text);
}

Output:

Tea 3.5 €; Cake 12.0 €

With brackets

The three-argument version of joining() adds a start and an end:

void main() {
    var ids = List.of(7, 12, 30);
    String sql = ids.stream().map(String::valueOf).collect(Collectors.joining(", ", "IN (", ")"));
 
    IO.println(sql);
}

Output:

IN (7, 12, 30)

Common mistake

Passing a list of numbers to String.join(). The method accepts only strings, and the code does not compile:

void main() {
    List<Integer> ids = List.of(1, 2, 3);
    IO.println(String.join(", ", ids));
}

Output:

Main.java:3: error: no suitable method found for join(String,List<Integer>)

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.