In Java, the java.util.stream.Collectors
class provides a number of useful methods for performing reductions on streams. Here are some commonly used ones:
-
toList()
: Collects all Stream elements into a List instance.
List<String> list = stream.collect(Collectors.toList());
-
toSet()
: Collects all Stream elements into a Set instance.
Set<String> set = stream.collect(Collectors.toSet());
-
toMap()
: Creates a Map instance from the Stream elements, with the first function serving as the map's keys and the second function as the values.
Map<String, Integer> map = stream.collect(Collectors.toMap(Function.identity(), String::length));
-
joining()
: Concatenates all Stream elements into a String.
String joined = stream.collect(Collectors.joining(", "));
-
counting()
: Counts the number of elements in the Stream.
Long count = stream.collect(Collectors.counting());
-
summingInt()
,summingLong()
,summingDouble()
: Sums the Stream elements.
Integer sum = stream.collect(Collectors.summingInt(Integer::intValue));
-
maxBy()
,minBy()
: Finds the maximum or minimum Stream element according to a provided Comparator.
Optional<String> max = stream.collect(Collectors.maxBy(Comparator.naturalOrder()));
-
collectingAndThen()
: Performs an additional finishing transformation.
List<String> unmodifiableList = stream.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
-
partitioningBy()
: Partitions the Stream elements into a Map according to a Predicate.
Map<Boolean, List<String>> partitioned = stream.collect(Collectors.partitioningBy(s -> s.length() > 5));
These are just a few examples. The Collectors
class provides many more utility methods for common tasks.
Top comments (0)