stream 分组 分区
分组 Collectors.groupingBy
分区 Collectors.partitioningBy
TestMain.java
package com.nenu;
import java.util.*;
import java.util.stream.Collectors;
public class TestMain {
public static void main(String[] args) {
Student s1 = new Student(1,"test1","111",1);
Student s2 = new Student(2,"test2","111",1);
Student s3 = new Student(3,"test3","222",0);
Student s4 = new Student(4,"test4","333",2);
Student s5 = new Student(5,"test5","444",0);
Set<String> stringSet = new HashSet<>();
stringSet.add("222");
stringSet.add("333");
List<Student> studentList = new ArrayList<>();
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
studentList.add(s4);
studentList.add(s5);
Map<Boolean, List<Student>> collect = studentList.stream().collect(Collectors.partitioningBy(student -> stringSet.contains(student.getCode())));
Map<Integer, List<Student>> collect1 = studentList.stream().collect(Collectors.groupingBy(Student::getStatus));
System.out.println("状态0="+collect1.get(0));
System.out.println("状态1="+collect1.get(1));
System.out.println("状态2="+collect1.get(2));
System.out.println("状态true="+collect.get(true));
System.out.println("状态false="+collect.get(false));
}
}
结果
状态0=[Student{id=3, code='222', status=0}, Student{id=5, code='444', status=0}]
状态1=[Student{id=1, code='111', status=1}, Student{id=2, code='111', status=1}]
状态2=[Student{id=4, code='333', status=2}]
状态true=[Student{id=3, code='222', status=0}, Student{id=4, code='333', status=2}]
状态false=[Student{id=1, code='111', status=1}, Student{id=2, code='111', status=1}, Student{id=5, code='444', status=0}]
Student.java
package com.nenu;
public class Student {
private Integer id;
private String name;
private String code;
private Integer status;
public Student(Integer id, String name, String code,Integer status) {
this.id = id;
this.name = name;
this.code = code;
this.status = status;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", code='" + code + '\'' +
", status=" + status +
'}';
}
}