In JavaScript, the Array.join() method offers a convenient way to concatenate elements of an array into a single string. Does Java offer a similar functionality?
If you want to create such a functionality from scratch, you can use StringBuilder:
static public String join(List<String> list, String conjunction) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String item : list) { if (first) first = false; else sb.append(conjunction); sb.append(item); } return sb.toString(); }
However, since Java 8, more efficient and elegant options are available:
To join a List
List<String> list = Arrays.asList("foo", "bar", "baz"); String joined = String.join(" and ", list); // "foo and bar and baz"
For collections with elements of types other than String, you can use the Collectors.joining collector with the Stream API:
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"
You may also consider using the StringJoiner class, which offers additional customization options:
StringJoiner joiner = new StringJoiner(", "); list.stream() .forEach(joiner::add); String joinedFirstNames = joiner.toString(); // "John, Anna, Paul"
The above is the detailed content of How to Efficiently Join a List of Strings in Java?. For more information, please follow other related articles on the PHP Chinese website!