Java 8 Streams Java Java API
The overloaded static methods, Collectors#reducing() return a Collector which perform a reduction on the input stream elements according to the provided binary operator.
<T> Collector<T,?,Optional<T>> reducing(BinaryOperator<T> op)
<T> Collector<T,?,T> reducing(T identity,
BinaryOperator<T> op)
<T,U> Collector<T,?,U> reducing(U identity,
Function<? super T,? extends U> mapper,
BinaryOperator<U> op)
Parameters
op: a BinaryOperator which reduces the input values
identity: The identity value for the reduction, i.e. for all input elements x:
op(identity,x) == x
mapper: a mapping function for input type T to U conversion.
Examples
package com.logicbig.example.collectors;
import java.util.stream.Collectors; import java.util.stream.Stream;
public class ReducingExample { public static void main (String[] args) { Stream<Integer> s = Stream.of(5, 10, 20, 50); Integer i = s.collect(Collectors.reducing((integer, integer2) -> integer2 - integer)) .orElse(-1);
System.out.println(i); } }
Output35
Original Post
package com.logicbig.example.collectors;
import java.util.stream.Collectors; import java.util.stream.Stream;
public class ReducingExample2 { public static void main (String[] args) { Stream<Integer> s = Stream.of(5, 10, 20, 50); Integer i = s.collect(Collectors.reducing(1, (integer, integer2) -> integer2 * integer)); System.out.println(i); } }
Output50000
Original Post
package com.logicbig.example.collectors;
import java.util.stream.Collectors; import java.util.stream.Stream;
public class ReducingExample3 { public static void main (String[] args) { Stream<Integer> s = Stream.of(5, 10, 20, 50).parallel(); String str = s.collect(Collectors.reducing( "", x -> Integer.toString(x), (s1, s2) -> s1 + s2)); System.out.println(str); } }
Output5102050
Original Post
|
|