JavaStream对List集合做分组统计
写代码时如果不想通过SQL查询做分组统计,通过Stream流也是可以做到的,现⽤简单demo记录⼀下。
先创建⼀个学⽣类
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
java stream@AllArgsConstructor
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
private Integer classNumber;
}
然后造⼏个数据,放到⼀个List⾥⾯
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<Student>();
studentList.add(new Student(1, "张三", "男", 20, 2));
studentList.add(new Student(2, "李四", "男", 21, 1));
studentList.add(new Student(3, "王五", "⼥", 19, 1));
studentList.add(new Student(4, "赵六", "男", 19, 1));
studentList.add(new Student(5, "王⼤锤", "男", 20, 2));
}
1.如果需要对学⽣集合按班级分组,则可以这样写
Map<Integer, List<Student>> studentGroup = studentList.stream().upingBy(Student::getClassNumber));
for(Map.Entry<Integer, List<Student>> entry : Set()){
System.out.println("key :"+Key()+", value :"+Value());
}
运⾏结果:
key :1, value :[Student(id=2, name=李四, sex=男, age=21, classNumber=1), Student(id=3, name=王五, sex=⼥, age=19, classNumber=1), Student(id=4, name= key :2, value :[Student(id=1, name=张三, sex=男, age=20, classNumber=2), Student(id=5, name=王⼤锤, sex=男, age=20, classNumber=2)]
2.如果是对学⽣按班级分组,并统计每个班的⼈数
Map<Integer, Long> map = studentList.stream().upingBy(Student::getClassNumber, unting()));
for(Map.Entry<Integer, Long> entry : Set()){
System.out.println("key :"+Key()+", value :"+Value());
}
运⾏结果
key :1, value :3 key :2, value :2

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。