Streams reduce with identity:
reduce() is a method provided as a part of streams api which comes handy when you want to implement your own reduction mechanism.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package ravi.tutorial.java.java8.lambda; import java.util.ArrayList; import java.util.List; public class StreamReduceWithIdentityExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("First"); list.add("Second"); list.add("Third"); list.add("Fourth"); String reducedString = list.stream().reduce("Zero", (result, element) -> { System.out.println("Result = " + result + " | Element = " + element); return result = result + " <" + element + ">"; }); System.out.println("Final reduced string = " + reducedString); } } |
Output:
1 2 3 4 5 |
Result = Zero | Element = First Result = Zero <First> | Element = Second Result = Zero <First> <Second> | Element = Third Result = Zero <First> <Second> <Third> | Element = Fourth Final reduced string = Zero <First> <Second> <Third> <Fourth> |