W3docs

Using streams to convert a list of objects into a string obtained from the toString method

You can use the map and collect methods of the Stream class to achieve this.

You can use the map and collect methods of the Stream class to achieve this. Here is an example:


List<Object> list = ...
String result = list.stream().map(Object::toString).collect(Collectors.joining(", "));

This will create a stream of the list, apply the toString method to each element of the stream, and then collect the resulting stream of strings into a single string, separated by commas.

Alternatively, you can use the reduce method to achieve the same result:


String result = list.stream().map(Object::toString).reduce((s1, s2) -> s1 + ", " + s2).orElse("");

This will concatenate the strings in the stream, starting with an empty string and using a comma as the separator. The orElse method is used to return an empty string if the stream is empty.