一些自己整理的demo,便于回顾。
1.遍历和处理业务
List<Integer> listScore = Arrays.asList(5, 20);
//遍历泛型为基本类型直接用使用接口
listScore.stream().forEach(System.out::println);
//遍历自定义的类 只能先定义对象student
list.stream().forEach(student -> System.out.println(student.toString()));
//遍历处理多行业务
list.stream().forEach(student -> {
String status = student.getScore() < 60 ? ":不合格" : ":合格";
student.setStatus(status);
});
2.筛选
//筛选60以下为不不及格 用于只有一次判断
list.stream().filter(student -> (student.getScore() < 60)).forEach(s -> s.setStatus("不及格"));
//把分数转化成一个新的集合
List<Integer> listScore = list.stream().map(student -> student.getScore()).collect(Collectors.toList());
//遍历泛型为基本类型直接用使用接口
listScore.stream().forEach(System.out::println);
//把60分以下的转化成一个新集合
List<Student> dStudent = list.stream().filter(student -> student.getScore() < 60).collect(Collectors.toList());
System.out.println("***不及格****");
dStudent.stream().forEach(student -> System.out.println(student.toString()));
3.合并+查找
Student stu3 = new Student("haiMianBaby", 90);
Student stu4 = new Student("paiDaXing", 100);
List<Student> studentList = Arrays.asList(stu3, stu4);
//把两个集合汇成一个集合
List<Student> allStudent = Stream.of(list, studentList).flatMap(students -> students.stream()).collect(Collectors.toList());
allStudent.stream().forEach(student -> System.out.println(student.toString()));
//寻找集合中最多对象
Student highScoreStudent = allStudent.stream().max(Comparator.comparing(student -> student.getScore())).get();
Student lowScoreStudent = allStudent.stream().min(Comparator.comparing(student -> student.getScore())).get();
System.out.println("分数最高:" + highScoreStudent.toString());
System.out.println("分数最低" + lowScoreStudent);
Student类
public class Student {
private String name;
private Integer score;
private String status = "无";
}