Using Java 8 to Convert a List of Objects to a String Derived from the toString () Method

There are many useful new things in Java 8. For example, I can iterate over a stream over a list of objects, and then sum the values ​​from a specific field of Object instances. For example.

 public class AClass { private int value; public int getValue() { return value; } } Integer sum = list.stream().mapToInt(AClass::getValue).sum(); 

So I ask if there is a way to build a String that combines the output of the toString() method from instances on a single line.

 List<Integer> list = ... String concatenated = list.stream().... //concatenate here with toString() method from java.lang.Integer class 

Assuming list contains integers 1 , 2 and 3 , I expect concatenated be "123" or "1,2,3" .

+134
java-8 java-stream
Jul 22 '14 at 8:54
source share
11 answers

One easy way is to add list items to StringBuilder

  List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); StringBuilder b = new StringBuilder(); list.forEach(b::append); System.out.println(b); 

You can also try:

 String s = list.stream().map(e -> e.toString()).reduce("", String::concat); 

Explanation: The map converts the Integer stream to a String stream, and then decreases as the union of all elements.

Note: this is a normal reduction that runs in O (n 2 )

for best performance, use a StringBuilder or mutable reduction similar to F. Beller's answer.

 String s = list.stream().map(Object::toString).collect(Collectors.joining(",")); 

Link: stream reduction

+265
Jul 22 '14 at 9:07
source share

There is a joining collector in the API. This is a static method in Collectors .

 list.stream().map(Object::toString).collect(Collectors.joining(",")) 

Not ideal due to the required toString call, but it works. Different delimiters are possible.

+146
Jul 22 '14 at 9:56 on
source share

Just in case, if someone tries to do this without java 8, there is a pretty good trick. List.toString () already returns a collection that looks like this:

[1,2,3]

Depending on your specific requirements, this can be handled until the list items contain [] or.

For example:

 list.toString().replace("[","").replace("]","") 

or if your data may contain square brackets:

 String s=list.toString(); s = s.substring(1,s.length()-1) 

will give you a pretty reasonable result.

One array element in each row can be created as follows:

 list.toString().replace("[","").replace("]","").replaceAll(",","\r\n") 

I used this method to create html hints from a list in a small application with something like:

 list.toString().replace("[","<html>").replace("]","</html>").replaceAll(",","<br>") 

If you have an array then start with Arrays.asList (list) .toString () instead

I completely agree that this is not optimal, but it is not as inefficient as you think, and it is quite simple to read and understand. This, however, is rather inflexible - in particular, do not try to separate replaceAll elements if your data can contain commas and use the substring version if you have square brackets in your data, but for an array of numbers this is pretty much perfect.

+9
Oct 28 '15 at 22:42
source share

Other answers are ok. However, you can also pass Collectors.toList () as a parameter to the Stream. collect () to return elements as an ArrayList.

 System.out.println( list.stream().map( e -> e.toString() ).collect( toList() ) ); 
+4
Dec 18 '14 at 9:06
source share
 String actual = list.stream().reduce((t, u) -> t + "," + u).get(); 
+1
Jan 05 '17 at 11:46 on
source share

StringListName = ObjectListName.stream (). Map (m β†’ m.toString ()). Collect (Collectors.toList ());

+1
Jan 07 '19 at 22:15
source share
 List<String> list = Arrays.asList("One", "Two", "Three"); list.stream() .reduce("", org.apache.commons.lang3.StringUtils::join); 

Or

 List<String> list = Arrays.asList("One", "Two", "Three"); list.stream() .reduce("", (s1,s2)->s1+s2); 

This approach also allows you to build a string result from a list of objects. Example

 List<Wrapper> list = Arrays.asList(w1, w2, w2); list.stream() .map(w->w.getStringValue) .reduce("", org.apache.commons.lang3.StringUtils::join); 

Here the Reduce function allows you to have some initial value to which you want to add a new line. Example:

  List<String> errors = Arrays.asList("er1", "er2", "er3"); list.stream() .reduce("Found next errors:", (s1,s2)->s1+s2); 
0
Dec 29 '17 at 7:54 on
source share

Testing both approaches proposed in Shail016 and bpedroso 's answer ( https://stackoverflow.com/a/16574/... ), a simple StringBuilder + append(String) in a for loop seems to run much faster than list.stream().map([...] .

Example: this code scans Map<Long, List<Long>> creates a json string using list.stream().map([...] :

 if (mapSize > 0) { StringBuilder sb = new StringBuilder("["); for (Map.Entry<Long, List<Long>> entry : threadsMap.entrySet()) { sb.append("{\"" + entry.getKey().toString() + "\":["); sb.append(entry.getValue().stream().map(Object::toString).collect(Collectors.joining(","))); } sb.delete(sb.length()-2, sb.length()); sb.append("]"); System.out.println(sb.toString()); } 

On my virtual machine, dev typically takes 0.35 to 1.2 seconds to run the junit test. While using this following code, it takes from 0.15 to 0.33 seconds:

 if (mapSize > 0) { StringBuilder sb = new StringBuilder("["); for (Map.Entry<Long, List<Long>> entry : threadsMap.entrySet()) { sb.append("{\"" + entry.getKey().toString() + "\":["); for (Long tid : entry.getValue()) { sb.append(tid.toString() + ", "); } sb.delete(sb.length()-2, sb.length()); sb.append("]}, "); } sb.delete(sb.length()-2, sb.length()); sb.append("]"); System.out.println(sb.toString()); } 
0
Sep 04 '18 at 15:31
source share

Can we try this.

 public static void main(String []args){ List<String> stringList = new ArrayList<>(); for(int i=0;i< 10;i++){ stringList.add(""+i); } String stringConcated = String.join(",", stringList); System.out.println(stringConcated); } 
-one
Feb 22 '16 at 13:09
source share

With Java 8+

 String s = Arrays.toString(list.stream().toArray(AClass[]::new)); 

Not the most efficient, but it is a solution with a bit of code.

-one
Nov 29 '17 at 0:23
source share

Alternatively, you can do it as follows.

  List<String> list = Arrays.asList("One", "Two", "Three"); String result = String.join(", ", list); System.out.println(result); 
-2
Oct 05 '17 at 12:31 on
source share



All Articles