Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList of Strings to one single string

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?"

like image 888
user1874239 Avatar asked Dec 04 '12 03:12

user1874239


People also ask

How do I convert a List to a single String in Java?

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.

Can we convert ArrayList to String?

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.

How do you concatenate a String in an ArrayList in Java?

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.


2 Answers

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());
}
like image 148
Cuga Avatar answered Oct 16 '22 06:10

Cuga


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.

like image 43
Goot Avatar answered Oct 16 '22 04:10

Goot