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.
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.
Use join
String joined2 = String.join(",", test );
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();
}
deleteCharAt(result.length()-1).toString() will take care of this.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.
test.toString().replaceAll( "[\\]\\[ ]", "" ) is not enough?ArrayUtils, and Vishnu has the right idea there (if you can use it).String.join(", ", List.of("one", "two", "three"));
This Java code snippet demonstrates a concise way to concatenate a list of strings into a single string, with a specified delimiter separating each element. It's particularly good for achieving this as a single, compact line of code.
Here's a breakdown:
List.of("one", "two", "three"): This creates an immutable list containing the strings "one", "two", and "three".
String.join(", ", ...): This is a static method of the String class introduced in Java 8. It takes two arguments:
The delimiter (in this case, ", " - a comma followed by a space) that will be placed between each element.
An Iterable (like our List) of elements to be joined.
The method efficiently iterates through the list and builds the resulting string. For the given example, the output will be: "one, two, three".