Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join String list elements with a delimiter in one step [duplicate]

Tags:

java

Is there a function like join that returns List's data as a string of all the elements, joined by delimiter provided?

 List<String> join; ....  String join = list.join('+");  // join == "Elem 1+Elem 2"; 

or one must use an iterator to manually glue the elements?

like image 313
EugeneP Avatar asked Oct 26 '10 08:10

EugeneP


People also ask

How do you join a list into a string in Java?

In Java, we can use String. join(",", list) to join a List String with commas.

How do you join a list of strings in Python?

If you want to concatenate a list of numbers ( int or float ) into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join() .


2 Answers

Java 8...

String joined = String.join("+", list); 

Documentation: http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-

like image 145
gahrae Avatar answered Sep 23 '22 01:09

gahrae


You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+"); 
like image 44
Romain Linsolas Avatar answered Sep 20 '22 01:09

Romain Linsolas