"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Efficiently Concatenate Lists of Strings in Java?

How Can I Efficiently Concatenate Lists of Strings in Java?

Posted on 2025-03-22
Browse:540

How Can I Efficiently Concatenate Lists of Strings in Java?

Java: Efficiently Concatenating Lists of Strings

In Java, there are several ways to combine multiple strings from a list into a single string. While one can manually create a loop and append each string to a StringBuilder, checking for the first string and adding a separator accordingly, this approach can be cumbersome.

Introducing String.join()

Java 8 introduced the String.join() method, which provides a concise way to concatenate a collection of Strings. Its syntax is as follows:

public static String join(CharSequence delimiter, Iterable extends CharSequence> elements)

Where:

  • delimiter: The separator to place between each element in the output string
  • elements: An iterable collection of CharSequences (i.e., Strings) to be joined

Example with String.join()

To join a list of strings using String.join():

List names = Arrays.asList("Josh", "Sarah", "David");
String joinedNames = String.join(", ", names); // "Josh, Sarah, David"

Collectors.joining() for Non-String Elements

For collections of non-String elements, you can leverage the Collectors.joining() method in conjunction with the stream API:

List people = Arrays.asList(
    new Person("John", "Smith"),
    new Person("Anna", "Martinez"),
    new Person("Paul", "Watson")
);

String joinedFirstNames = people.stream()
    .map(Person::getFirstName)
    .collect(Collectors.joining(", ")); // "John, Anna, Paul"

StringJoiner for More Control

The StringJoiner class provides even more control over the concatenation process. It allows setting prefixes, suffixes, and delimiters for the resulting string. Its syntax is:

public class StringJoiner {
    StringJoiner(CharSequence delimiter)
}

Example with StringJoiner

StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.add("Apple");
joiner.add("Orange");
joiner.add("Banana");

String result = joiner.toString(); // "[Apple, Orange, Banana]"
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3