Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a List of Strings into a single String using ArrayUtils in java

Tags:

java

arrays

I have below code

List<String> test = new ArrayList<String>();
test.add("one");
test.add("two");
test.add("three");

Need output as "one,two,three" in a single string using Array Utils. Need a single line solution.

like image 300
Nithyn. K Avatar asked Dec 01 '22 17:12

Nithyn. K


2 Answers

You can't do this with ArrayUtils. You can use Apache's StringUtils join function to get the result you want.

// result is "one,two,three"
StringUtils.join(test, ',');

If you don't want to use a library, you can create this function:

public static String joiner(List<String> list, String separator){
    StringBuilder result = new StringBuilder();
    for(String term : list) result.append(term + separator);
    return result.deleteCharAt(result.length()-separator.length()).toString();
} 
like image 23
Algorithmatic Avatar answered Dec 03 '22 07:12

Algorithmatic


Use join

String joined2 = String.join(",", test );
like image 159
Vishnu Avatar answered Dec 03 '22 06:12

Vishnu