Home > Java > javaTutorial > How to Efficiently Join a List of Strings in Java?

How to Efficiently Join a List of Strings in Java?

Linda Hamilton
Release: 2024-12-24 19:42:11
Original
352 people have browsed it

How to Efficiently Join a List of Strings in Java?

Converting a List to a Joined String in Java

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();
}
Copy after login

However, since Java 8, more efficient and elegant options are available:

String.join

To join a List specifically, you can use the String.join() method:

List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"
Copy after login

Collectors.joining

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"
Copy after login

StringJoiner

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"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template