Stream API is an API that performs aggregation operations based on data sources such as collections and arrays. This article describes the Collectors class, which is one of the termination operations. The Collectors class implements the Collector interface. The collect () method can collect elements from a stream into one object.
(1) <R,A> R collect(Collector<? super T,A,R> collector) (2) <R> R collect(Supplier<R> supplier,BiConsumer<R ? superT> accumulator, BiConsumer<R,R> combiner)
(1) Collector<T,?,List<T>> toList() (2) Collector<T,?,Integer> summingInt() (3) Collector<T,?,Double> averagingInt()
Myclass.java
Stream<String> stream = Steam.of("aa","bb","cc");
//List streams with toList
List<String> result1 = stream.collect(Collectors.toList());
System.out.print(result1); //[aa,bb,cc]
//summingInt gives the sum of all the bundles
Integer result2 = stream.collect(Collectors.summingInt(x->x.length());
System.out.print(result2); //6
//averagingInt finds the mean of streams
Double result3 = stream.collect(Collectors.averagingInt(x->x.length()));
System.out.print(result2); //2.0
Regarding the Colectors class, it has the image of "execution processing as a whole".
Recommended Posts