Java使用stream对集合类进行操作
1.背景
在Java 的开发中的,对集合的使用是最频繁的,如何高效简洁快速的对集合类进行操作直接影响到我们的工作效率和代码的性能,这一篇文章是对日常工作经常使用的方法的总结
2.常用方法及其示例
//有个Student类 和这个类的list
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private Integer id; //学号
private String name; //名字
private String gender; //性别
private String className; //班级
private Double chinese; //语文
private Double math; //数学
private Double english; //英语
}
List<Student> students=new ArrayList<>();
students.add(new Student(1,"zs","男","高三1班",124.2,135.2,105.5));
students.add(new Student(2,"ls","女","高三2班",124.2,135.2,85.5));
students.add(new Student(3,"ww","女","高三1班",144.2,125.2,105.5));
students.add(new Student(4,"zl","男","高三3班",124.2,135.2,95.5));
students.add(new Student(5,"lq","女","高三2班",134.2,135.2,125.5));
students.add(new Student(6,"hz","男","高三3班",124.2,35.2,105.5));
1.如果想对list对象某个属性进行分组,可以使用Collectors.groupingBy()方法,例如各班的成绩的情况 可以先进行分组 使用以下代码完成对班级的分组
System.out.println("按照班级进行分类:");
Map<String, List<Student>> studentsByClass = students.stream()
.collect(Collectors.groupingBy(Student::getClassName)); //按照班级进行分组
// 得到一个以班级为主键的map
2.如果想得到list对象某个属性的最大最小值 可以使用max min 如现在想得到数学第一名同学的信息 可以使用以下方法
System.out.println("得到数学第一名的方法:");
Optional<Student> topMathStudent = studentList.stream()
.max(Comparator.comparing(Student::getMath)); //得到数学第一名
if (topMathStudent.isPresent()) {
Student student = topMathStudent.get();
// 获取该学生的信息
}
3.想得到数学的平均成绩 可以使用下面方法
//得到数学的平均成绩
studentList.stream()
.mapToDouble(Student::getMath)
.average()
.orElse(Double.NaN);
4.按照英语成绩实现从高到低的排序
List<Student> sortedList = studentList.stream()
.sorted(Comparator.comparing(Student::getEnglish).reversed()) //从高到低的排序
.collect(Collectors.toList());
5.按照语文成绩从低到高排序
List<Student> sortedList = studentList.stream()
.sorted(Comparator.comparing(Student::getChinese)) //从低到高排序
.collect(Collectors.toList());
6.得到list中所有男生对象,并按照数学从高到底进行排序
List<Student> sortedMaleStudents = studentList.stream()
.filter(student -> "男".equals(student.getGender())) //条件过滤方法
.sorted(Comparator.comparing(Student::getMath).reversed())
.collect(Collectors.toList());