1、基础类
package cn.fqy.test; public class Student { // 名称 private String name; // 性别 private String gender; // 年龄 private Integer age; public Student(String name, String gender, Integer age) { this.name = name; this.gender = gender; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", gender='" + gender + '\'' + ", age=" + age + '}'; } }
2、测试类
package cn.fqy.test; import java.util.ArrayList; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static java.util.stream.Collectors.averagingInt; import static java.util.stream.Collectors.partitioningBy; public class ListSort { public static void main(String[] args) { // 测试数据 List<Student> list = new ArrayList<>(); list.add(new Student("李明","男",18)); list.add(new Student("李飞","男",17)); list.add(new Student("张丽","女",17)); list.add(new Student("张艳","女",20)); list.add(new Student("王朋","男",18)); list.add(new Student("陈晴","女",18)); list.add(new Student("王菲","女",19)); list.add(new Student("李雷","男",20)); // 查找性别为男的学生 List<Student> boys = list.stream().filter(s->"男".equals(s.getGender())).collect(Collectors.toList()); // map的key值true为男,false为女的集合 Map<Boolean, List<Student>> map1 = list.stream().collect(partitioningBy(student -> student.getGender().equals("男"))); // 求性别为男的学生总岁数 Integer sum = list.stream().filter(s -> "男".equals(s.getGender())).mapToInt(Student::getAge).sum(); // 按性别进行分组统计人数 Map<String, Integer> map2 = list.stream().collect(Collectors.groupingBy(Student::getGender, Collectors.summingInt(p -> 1))); // 判断是否有年龄大于25岁的学生 boolean check = list.stream().anyMatch(student -> student.getAge() > 25); // 获取所有学生的姓名集合 List<String> list2 = list.stream().map(Student::getName).collect(Collectors.toList()); // 求所有人的平均年龄 double avg = list.stream().collect(averagingInt(Student::getAge)); // 求年龄最大的学生 Student s = list.stream().reduce((student, student2) -> student.getAge() > student2.getAge() ? student:student2).get(); // 按照年龄从小到大排序 List<Student> l3 = list.stream().sorted((s1, s2) -> s1.getAge().compareTo(s2.getAge())).collect(Collectors.toList()); // 获取所有的名字,输出一个字符串 String str = list.stream().map(Student::getName).collect(Collectors.joining(",", "[", "]")); System.out.println(str); // 获取年龄的最大值、最小值、平均值、求和等等 IntSummaryStatistics intSummaryStatistics = list.stream().mapToInt(Student::getAge).summaryStatistics(); System.out.println(intSummaryStatistics); } }