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?"
Using StringBufferCreate an empty String Buffer object. Traverse through the elements of the String array using loop. In the loop, append each element of the array to the StringBuffer object using the append() method. Finally convert the StringBuffer object to string using the toString() method.
To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.
Java – Join Elements of ArrayList<String> with Delimiter To join elements of given ArrayList<String> arrayList with a delimiter string delimiter , use String. join() method. Call String.
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());
}
Use StringUtils to solve this.
e.g. Apache Commons Lang offers the join method.
StringUtils.join(myList,","))
It will iterate through your array or list of strings and will join them, using the 2nd parameter as seperator. Just remember - there is always a library for everything to make things easy.
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