Collectors.reducing for joining Strings
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectorReduceFlight {
public static void main(String[] dataBag) {
List<Person> persons = Arrays.asList(
new Person("raj"),
new Person("rose"),
new Person("jack")
);
String names = persons
.stream()
.map(Person::getName)
.collect(Collectors.reducing((s1, s2) ->s1+s2))
.get();
System.out.println("1) Names: "+ names);
String temps = persons.stream()
.collect( Collectors.reducing(
"2) Names: ",
Person::getName,
(s1, s2) -> s1 + s2 ));
System.out.println(temps);
}
}
Output:
Names: rajrosejack
Names: rajrosejack
Explanation:
Collectors.reducing((s1, s2) ->s1+s2):
Takes name of each person object in String stream and then reducing the resulting string stream using a String accumulator and the appends to it the name of each person.
If the stream is empty then it will throw an Exception. NoSuchElementException.
Collectors.reducing("2) Names: ", Person::getName, (s1, s2) -> s1 + s2 )):
This starts the reduction process with the string "2) Names: ".
If the stream is empty then it will return only "2) Names: ".
In this example it takes the each person name and join all the names with prepended string as "2) Names:"