Java streams - should I use reduce or collect?

Java Impatient :

I use Java 9. I am learning about Stream operations like collect() and reduce() from this tutorial by Baeldung i.e. EUGEN PARASCHIV.

I have to list all the employee names separated by a comma. The tutorial uses collect() to do that. But, I can do it with reduce() and collect(). I have seen some examples which use collect only to put elements into a collection such as List. So, how do I know when to use reduce() or collect() ?

private static Employee[] arrayOfEmps = {
        new Employee(1, "Jeff Bezos", 100000.0),
        new Employee(2, "Bill Gates", 200000.0),
        new Employee(3, "Mark Zuckerberg", 300000.0)
};


public static void joiningDemo(){
    //List all the employee names separated by a comma.
    String fromReduce = empList.stream().map(Employee::getName).reduce("", (allNames, oneName) ->  allNames + ", " + oneName);
    fromReduce = fromReduce.substring(2);    
    String fromCollect = empList.stream().map(Employee::getName).collect(Collectors.joining(", "));

    System.out.println("reduce : " + fromReduce);
    System.out.println("collect : " + fromCollect);
}

OUTPUT :

reduce : Jeff Bezos, Bill Gates, Mark Zuckerberg
collect : Jeff Bezos, Bill Gates, Mark Zuckerberg
Bohemian :

Collectors.joining(", ") is basically a reduction - all elements melded together into one value - but it adheres to the contract of a collector because it keeps its own state.

Although it would be instructive for you to implement it as a reduction, I would use Collectors.joining() because 99% of the code is written for you.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=194679&siteId=1