一、准备工作
1.创建一个Student对象
2.创建一个测试类,创建list集合,向list中添加数据
@Test public void test2(){ List<Student> studentList = new ArrayList<>(); Student s1 = new Student("1","小张",20,"男","0"); Student s2 = new Student("2","wxdqd",22,"男","1"); Student s3 = new Student("3","冷酷的大米",21,"女","1"); Student s4 = new Student("4","lldmt",18,"女","2"); Student s5 = new Student("5","小流",28,"男","2"); Student s6 = new Student("6","axdjm",25,"男","0"); Student s7 = new Student("7","axdjm",25,"男","0"); Student s8 = new Student("8","axdjm",25,"男","0"); studentList.add(s1); studentList.add(s2); studentList.add(s3); studentList.add(s4); studentList.add(s5); studentList.add(s6); studentList.add(s7); studentList.add(s8);二、利用java8特性Stream流对list集合进行操作
1.利用stream流进行foreach遍历
2.对studentList利用filter函数进行筛选 获取符合条件的
3.对List集合进行去重
//将username相同的 进行去重List<Student> unique = studentList.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getUsername))),ArrayList :: new));unique.stream().forEach(student -> { System.out.println("-------------------"+student.getUsername()); });4.取出list集合对象中的某一个属性(取出list中的每一个对象的名字组成一个新的集合)
List<String> username=studentList.stream().map(Student::getUsername).collect(Collectors.toList());//不取重的List<String> username = studentList.stream(),map(Student::getUsername).distinct().collect(Collectors.toList());//这个是将名字取重之后的5.过滤属性为空的字段(添加一条数据 名字为空的数据) //获取名字不为空的
Student s9 = new Student("9","",25,"男","0"); studentList.add(s9); List<String> IsEmptyUsernameList= studentList.stream().map(s-> s.getUsername()).filter(s-> !s.isEmpty()).collect(Collectors.toList()); System.out.println(IsEmptyUsernameList);6.根据其中的某一属性值进行计算
//(获取年龄的最大值、最小值、平均值、综合、个数)