Reputation: 111
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.
Upvotes: 6
Views: 27695
Reputation: 1892
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();
}
Upvotes: 3
Reputation: 1
List<String> test = new ArrayList<String>();
test.add("one");
test.add("two");
test.add("three");
Iterator it = test.iterator();
while(it.hasNext()){
String s=it.next();
StringBuilder sb = new StringBuilder();
sb.append(s);
}
Upvotes: -1
Reputation: 201409
If you must use ArrayUtils
then you could use List.toArray(T[])
(because ArrayUtils
is for arrays) and a regular expression to remove {
and }
on one line like
List<String> test = new ArrayList<>(Arrays.asList("one", "two", "three"));
System.out.println(ArrayUtils.toString(test.toArray(new String[0]))
.replaceAll("[{|}]", ""));
Output is (as requested)
one,two,three
The String.join(CharSequence, Iterable<? extends CharSequence>)
suggested by @Vishnu's answer offers a solution that eschews ArrayUtils
(but is arguable better, assuming you can use it) with
String joined2 = String.join(",", test);
System.out.println(joined2);
which outputs the same.
Upvotes: 0