Difference: Java 8 stream reduce vs collect




Asked on September 27, 2016
What is the difference between Java 8 stream reduce() and collect() method?


Replied on September 30, 2016
1.   reduce() method always creates a  new value whereas collect() method updates or mutates an existing value.
     
2.  reduce() performs reduction whereas collect() performs mutable reduction.   

3.   Suppose we are want summation then using reduce(), we use as follows
 
List<Integer> list = Arrays.asList(3,2,5,6);
int sum = list.stream().reduce(0, Integer::sum);
System.out.println(sum);
 
And using collect(),  we calculate sum as follows.
 
IntSummaryStatistics stats = list.stream().collect(Collectors.summarizingInt(i->i));
System.out.println(stats.getSum());
 
 
4. In parallel processing  reduce() and collect() both uses combiner.   reduce() works as follows.
 
 
public class ReduceDemo3 {
    public static void main(String[] args) {
      List<Integer> list2 = Arrays.asList(2, 3, 4);
      //Here result will be 2*2 + 2*3 + 2*4 that is 18.
      int res = list2.parallelStream().reduce(2, (s1, s2) -> s1 * s2, (p, q) -> p + q);
      System.out.println(res);
   }
}
 
 Find the URL 


And collect() works as follows.
 
public class StreamCollect {
                public static void main(String[] args) {
                    List<String> list = Arrays.asList("Mukesh", "Vishal", "Amar");
                    String result = list.parallelStream().collect(StringBuilder::new,
                                                (response, element) -> response.append(" ").append(element),
                                                (response1, response2) -> response1.append(",").append(response2.toString()))
                                                .toString();
                    System.out.println("Result: " + result);
                }
}

Find the URL

 
 
 
 
 
 


Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us