Collectors .partitioningBy
时间: 2024-02-10 09:27:26 浏览: 71
Collectors.partitioningBy is a static method in the Java Collectors class. It is used to partition elements of a stream into two groups based on a given predicate. The method takes the predicate as an argument and returns a Collector that accumulates the elements into a Map<Boolean, List<T>>, where the keys are true and false representing the two groups.
Here's an example usage:
```java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Map<Boolean, List<Integer>> evenOddPartition = numbers.stream()
.collect(Collectors.partitioningBy(num -> num % 2 == 0));
List<Integer> evenNumbers = evenOddPartition.get(true);
List<Integer> oddNumbers = evenOddPartition.get(false);
System.out.println("Even numbers: " + evenNumbers);
System.out.println("Odd numbers: " + oddNumbers);
```
Output:
```
Even numbers: [2, 4, 6, 8, 10]
Odd numbers: [1, 3, 5, 7, 9]
```
In this example, the numbers are partitioned into even and odd groups using the predicate `num -> num % 2 == 0`. The resulting map contains two entries: one with the key true for even numbers and one with the key false for odd numbers.
阅读全文