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:
Example with String.join()
To join a list of strings using String.join():
Listnames = 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:
Listpeople = 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]"
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