Java 8 Collectors.partitioningBy
是一种将流的元素始终分为两部分的方法。
它返回一个在Map
中存储值的收集器。
在Map
中的key
只能是true
或false
。
此方法接收一个Predicate
和返回一个Collector(收集器)
。
语法如下
public static <T> Collector<T,?,Map<Boolean,List<T>>> partitioningBy(Predicate<? super T> predicate)
代码示例
Student.java
package com.concretepage.util.stream;
public class Student {
private String name;
private int age;
public Student(String name,int age){
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
我们将根据学生的年龄来划分他们。例如,我们将所有20岁的学生进行分区。年龄超过20岁的学生将是一个分区,其余的将是另一个分区。
核心代码
Map<Boolean, List<Student>> stdByClass = list.stream().collect(Collectors.partitioningBy(s -> s.getAge() > 20));
Collectors.partitioningBy
接受将被定义为返回true或false的Predicate
。
这个Predicate
应用于流的所有元素。
Collectors.partitioningBy
通过Stream.collect
方法返回一个Map
收集器。
在Map
中的key
只能是true
或false
。
CollectorsPartitioningBy.java
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class CollectorsPartitioningBy {
public static void main(String[] args) {
Student s1 = new Student("Ram", 18);
Student s2 = new Student("Shyam",22);
Student s3 = new Student("Mohan",19);
Student s4 = new Student("Mahesh",20);
Student s5 = new Student("Krishna",21);
List<Student> list = Arrays.asList(s1,s2,s3,s4,s5);
//partition of Student on the basis of age
System.out.println("----Partition of Student on the basis of age >20 ----");
Map<Boolean, List<Student>> stdByClass = list.stream()
.collect(Collectors.partitioningBy(s -> s.getAge() > 20));
stdByClass.forEach((k,v)->System.out.println("Key:"+k+" "+
((List<Student>)v).stream().map(s->s.getName()).collect(Collectors.joining(","))));
}
}
输出
----Partition of Student on the basis of age >20 ----
Key:false Ram,Mohan,Mahesh
Key:true Shyam,Krishna