ArrayList of Strings to one single string
arraylist, java, string
Solution
As of Java 8, this has been added to the standard Java API:
`String.join()` methods:
String joined = String.join("/", "2014", "10", "28" ); // "2014/10/28"
List<String> list = Arrays.asList("foo", "bar", "baz");
joined = String.join(";", list); // "foo;bar;baz"
`StringJoiner` is also added:
StringJoiner joiner = new StringJoiner(",");
joiner.add("foo");
joiner.add("bar");
joiner.add("baz");
String joined = joiner.toString(); // "foo,bar,baz"
Plus, it's nullsafe, which I appreciate. By this, I mean if `StringJoiner` encounters a `null` in a `List`, it won't throw a NPE:
@Test
public void showNullInStringJoiner() {
StringJoiner joinedErrors = new StringJoiner("|");
List<String> errorList = Arrays.asList("asdf", "bdfs", null, "das");
for (String desc : errorList) {
joinedErrors.add(desc);
}
assertEquals("asdf|bdfs|null|das", joinedErrors.toString());
}
Problem
I have an array list of strings (each individual element in the array list is just a word with no white space) and I want to take each element and append each next word to the end of a string. So say the array list has ``` element 0 = "hello" element 1 = "world," element 2 = "how" element 3 = "are" element 4 = "you?" ``` I want to make a string called sentence that contains "hello world, how are you?"