Home >Java >javaTutorial >How Can I Efficiently Join Array Elements with a Separator in Java?

How Can I Efficiently Join Array Elements with a Separator in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 19:29:11285browse

How Can I Efficiently Join Array Elements with a Separator in Java?

Join Array Elements with a Separator in Java

Question:

Seeking an efficient way to concatenate array elements with a specified separator, akin to the inverse operation of splitting.

Solution:

Using Java 8's String.join() Method:

Java 8 introduces a convenient method called String.join(), which streamlines this task:

String joinedString = String.join(delimiter, elements);

where:

  • delimiter is the separator to be inserted between elements.
  • elements can be specified directly, as an array, or as an iterable.

This method works in a straightforward manner:

  • Direct Element Specification:

    String joined1 = String.join(",", "a", "b", "c");
  • Array Input:

    String[] array = {"a", "b", "c"};
    String joined2 = String.join(",", array);
  • Iterable Input:

    List<String> list = Arrays.asList(array);
    String joined3 = String.join(",", list);

Using String.join() ensures an efficient and concise solution for combining array elements with a separator in Java.

The above is the detailed content of How Can I Efficiently Join Array Elements with a Separator in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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