The new class java.util.stream.Collectors in Java 8 implements the java.util.stream.Collector interface, and provides a large number of methods to perform map and reduce operations, or statistical operations on stream elements. In this chapter, we will take a look at some commonly used methods and write a few examples to practice.
Collectors.averagingDouble(): This method calculates the average of all elements in the stream when viewed as double type elements. The method returns the same Collectors instance, allowing for chained operations. It takes a parameter, which is a lambda expression used to map all elements before executing the averaging operation.
For example, the code below uses the collect() method to collect all elements and then passes them to the Collectors.averagingDouble(d->d*2) collector, which performs a *2 operation on each element before calculating the average value.
Collectors.averagingInt() and Collectors.averagingLong() work similarly to Collectors.averagingDouble(), but they treat the elements as int and long types respectively.
Collectors.collectingAndThen() is similar to map and reduce. It takes two parameters, the first one for reduce operation, and the second one for map operation. It first passes all elements in the stream to the second parameter, generates a collection, and then passes it to the first parameter for processing.
Collectors.counting() is used to count the number of elements in the stream.
Collectors.joining() combines all elements into a single string, with optional prefix and suffix.
Collectors.maxBy() and Collectors.minBy() are used to calculate the maximum and minimum values in the stream, and can accept a comparator as an argument for how to calculate these values.
Collectors.summingInt(), Collectors.summingLong(), and Collectors.summingDouble() calculate the sum of all elements in the stream, considering them as int, long, and double types respectively.
Collectors.toList(), Collectors.toSet(), and Collectors.toMap() are used to collect elements in the stream into a list, set, and map, respectively.
Collectors.mapping() is generally used in multiple map and reduce operations. It takes a function for mapping and a downstream collector for reduction.
Finally, we have a sample code that demonstrates the use of Collectors in Java 8 for various operations.
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删