In JavaScript, the Array.join() method provides a convenient way to concatenate elements of an array into a single string. Java, however, lacks a built-in equivalent.
Certain approaches involve manually constructing the joined string using a loop and a StringBuilder. While this method offers flexibility, it may be inefficient for large collections.
With the introduction of Java 8, a more elegant and efficient solution emerged: String.join(). This method allows you to directly join a collection of Strings using a specified delimiter:
List<String> list = Arrays.asList("foo", "bar", "baz"); String joined = String.join(" and ", list); // "foo and bar and baz"
For non-String collections, the Stream API can be utilized along with the joining Collector:
List<Person> list = Arrays.asList( new Person("John", "Smith"), new Person("Anna", "Martinez"), new Person("Paul", "Watson ") ); String joinedFirstNames = list.stream() .map(Person::getFirstName) .collect(Collectors.joining(", ")); // "John, Anna, Paul"
The StringJoiner class provides additional control over the joining process, such as specifying a prefix and suffix for the resulting string:
StringJoiner sj = new StringJoiner(", ", "[", "]"); for (String s : list) { sj.add(s); } String joined = sj.toString(); // "[foo, bar, baz]"
By incorporating these methods into your Java toolkit, you can efficiently join elements from lists or other collections, ensuring seamless string concatenation operations.
The above is the detailed content of How Can I Efficiently Join a List of Strings in Java?. For more information, please follow other related articles on the PHP Chinese website!