Java Collectors: Usage Guide
In Java, Collectors is a utility class within the Stream API that is used for performing collection operations on elements within a stream, such as collecting, grouping, filtering, etc.
Collectors offers a variety of static methods, commonly used methods include:
- Collect the elements in the Stream into a List using toList().
- toSet(): Collect the elements in the Stream to a Set.
- joining(): Concatenate the elements in a Stream into a single string.
- groupingBy(): group elements in the Stream by a specified condition.
- Counting(): Count the number of elements in the Stream.
- calculating the sum:求和
- find the maximum value, find the minimum value
Sample code:
List<String> list = Arrays.asList("apple", "banana", "cherry");
List<String> collectedList = list.stream().collect(Collectors.toList());
Map<Integer, List<String>> groupByLength = list.stream().collect(Collectors.groupingBy(String::length));