Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

JavaScript has Array.join()

js>["Bill","Bob","Steve"].join(" and ") Bill and Bob and Steve

Does Java have anything like this? I know I can cobble something up myself with 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(); }

...but there's no point in doing this if something like it is already part of the JDK.

1 Answer

0 votes
by (46k points)

With Java 8 you can perform this without any third party library.

If you need to join a Collection of Strings you can perform the new String.join() method:

List<String> list = Arrays.asList("shoo", "dar", "fzz");

String joined = String.join(" and ", list); // "shoo and dar and fzz"

If you have a Collection with another type than String you can use the Stream API with the joining Collector:

List<Person> list = Arrays.asList(

  new Person("Amy", "Shamy"),

  new Person("Nanna", "mann"),

  new Person("Pool", "Watt")

);

a

String joinedFirstNames = list.stream()

  .map(Person::getFirstName)

  .collect(Collectors.joining(", ")); // "Amy, Nanna, Pool"

The StringJoiner class may also be useful.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...