赞
踩
1. 集合去重: List<String> strList = list.stream().distinct().collect(Collectors.toList()); List<Student> list = Students.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(Student::getId))), ArrayList::new));//对象集合去重 2.交集 List<String> strList = strList1.stream().filter(str->strList2.contains(str)).collect(Collectors.toList); List<Student> students= students1.stream().filter(item ->students2.stream().map(e -> e.getName()).collect(Collectors.toList()).contains(item.getName())).collect(Collectors.toList());//对象集合求交集 3.差集 List<String> strList = strList1.stream().filter(str->!strList2.contains(str)).collect(Collectors.toList); List<Student> students= students1.stream().filter(item -> !students2.stream().map(e -> e.getName()).collect(Collectors.toList()).contains(item.getName())).collect(Collectors.toList());//对象集合求差集 4.排序 students.sort(Comparator.comparing(Student::getId).thenComparing(Student::getName));//对象集合升序排序 students.sort(Comparator.comparing(Student::getId).reversed().thenComparing(Student::getName));//对象集合倒序排序 5.List转化Map Map<String, Student> studentMap = students.parallelStream().collect(Collectors.toMap(Student::getId, Function.identity(), (v1, v2) -> v2));//对象集合转Map 6.获取list对象的某个字段组装成新list List<String> studentIdList = students.stream().map(student-> student.getId()).collect(Collectors.toList()); 7.求最值 int minAge = students.stream().map(Student::getAge).min(Integer::compareTo).get();//最小值 int maxAge = students.stream().map(Student::getAge).max(Integer::compareTo).get();//最大值 8.求和 int sumAge = students.stream().mapToInt(Student::getAge).sum();//基本类型 9.分组 Map<String, List<Student>> groupBySex = students.stream().collect(Collectors.groupingBy(Student::getSex));//按性别分组 10.forEach循环: forEach循环可以用return做跳过操作,而不能用break(会在编译期报错); 11.Comparator.comparing排序: Comparator.comparing默认是升序排序,可以用reversed改成降序 students.sort(Comparator.comparingLong(Student::getAge));
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。