public static void main(String[] args)throws Exception {
List students = new ArrayList<>();
students.add(new Student(1,"lisa",2));
students.add(new Student(2,"lisa",8));
students.add(new Student(3,"lisa",6));
students.add(new Student(5,"lisa",12));
//过滤出所有姓名为lisa学生 重点:filter
students = students.stream().filter(student -> student.getName().equals("lisa")).collect(Collectors.toList());
//过滤出所有姓名为lisa并且年龄大于5岁的学生 重点:filter可以叠加使用
students = students.stream().filter(student -> student.getName().equals("lisa"))
.filter(student -> student.getAge()>5)
.collect(Collectors.toList());
//取出所有学生的id 重点:map
List ids = students.stream().map(student -> student.getId()).collect(Collectors.toList());
//判断所有学生的年龄是否都大于5岁 重点:allMatch
boolean checkResult1 = students.stream().allMatch(student -> student.getAge() > 5);
//判断所有学生中是否有年龄大于5岁的 重点:anyMatch
boolean checkResult2 = students.stream().anyMatch(student -> student.getAge() > 5);
//根据年龄倒序排序 重点:sorted Comparator.comparing().reversed()
students = students.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
//根据年龄正序排序 重点:sorted Comparator.comparing()
students = students.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
//去除重复数据 重点:distinct
students = students.stream().distinct().collect(Collectors.toList());
//根据姓名和年龄去除重复数据
students.stream().collect(Collectors.collectingAndThen(Collectors.
toCollection(() -> new TreeSet<>(Comparator.comparing(student -> student.getName()+student.getAge()))), ArrayList::new));
//为每个学生加一岁 重点:forEach
students.stream().forEach(student -> student.setAge(student.getAge() + 1));
//为每个学生加一岁 并且姓名加* 重点:当forEach中有多条语句时可以通过大括号这种写法来满足我们的需求
students.stream().forEach(student -> {
student.setAge(student.getAge() + 1);
student.setName(student.getName() + "*");
});
}
由于水平有限,博客中难免会有一些错误,有纰漏之处恳请各位大佬不吝赐教!



