JavaScript has Array.join()
js>[\"Bill\",\"Bob\",\"Steve\"].join(\" and \")
Bill and Bob and Steve
Does Java have anything
Google's Guava API also has .join(), although (as should be obvious with the other replies), Apache Commons is pretty much the standard here.
Three possibilities in Java 8:
List<String> list = Arrays.asList("Alice", "Bob", "Charlie")
String result = String.join(" and ", list);
result = list.stream().collect(Collectors.joining(" and "));
result = list.stream().reduce((t, u) -> t + " and " + u).orElse("");
Not out of the box, but many libraries have similar:
Commons Lang:
org.apache.commons.lang.StringUtils.join(list, conjunction);
Spring:
org.springframework.util.StringUtils.collectionToDelimitedString(list, conjunction);
With a java 8 collector, this can be done with the following code:
Arrays.asList("Bill", "Bob", "Steve").stream()
.collect(Collectors.joining(" and "));
Also, the simplest solution in java 8:
String.join(" and ", "Bill", "Bob", "Steve");
or
String.join(" and ", Arrays.asList("Bill", "Bob", "Steve"));
On Android you could use TextUtils class.
TextUtils.join(" and ", names);
java.util.StringJoiner
Java 8 has got a StringJoiner class. But you still need to write a bit of boilerplate, because it's Java.
StringJoiner sj = new StringJoiner(" and ", "" , "");
String[] names = {"Bill", "Bob", "Steve"};
for (String name : names) {
sj.add(name);
}
System.out.println(sj);