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.
In Java, we can use String. join(",", list) to join a List String with commas.
extends E> c) method of the class java. util. ArrayList appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. Using this method you can concatenate two lists.
String.join
With Java 8 you can do this without any third party library.
If you want to join a Collection of Strings 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"
Collectors.joining
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("John", "Smith"),
new Person("Anna", "Martinez"),
new Person("Paul", "Watson ")
);
String joinedFirstNames = list.stream()
.map(Person::getFirstName)
.collect(Collectors.joining(", ")); // "John, Anna, Paul"
The StringJoiner
class may also be useful.
All the references to Apache Commons are fine (and that is what most people use) but I think the Guava equivalent, Joiner, has a much nicer API.
You can do the simple join case with
Joiner.on(" and ").join(names)
but also easily deal with nulls:
Joiner.on(" and ").skipNulls().join(names);
or
Joiner.on(" and ").useForNull("[unknown]").join(names);
and (useful enough as far as I'm concerned to use it in preference to commons-lang), the ability to deal with Maps:
Map<String, Integer> ages = .....;
String foo = Joiner.on(", ").withKeyValueSeparator(" is ").join(ages);
// Outputs:
// Bill is 25, Joe is 30, Betty is 35
which is extremely useful for debugging etc.
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);
On Android you could use TextUtils class.
TextUtils.join(" and ", names);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With