【java】lambda表达式之List操作
去重
//按学生姓名去重
//可能会改变原有list的顺序
List<Student> list = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));
//直接去重
List<Student> list = studentList.stream().distinct().collect(Collectors.toList());
过滤
//按学生姓名过滤
List<Student> list = studentList.stream().filter(item -> "张三".equals(item.getName())).collect(Collectors.toList());
抽取
//按学生姓名抽取形成新对象Person
List<Person> personList = studentList.stream().map(s->{
Person person = new Person();
person .setName(s.getName());
return person ;
}).collect(Collectors.toList());
//按学生id抽取形成map集合
Map<Long, Person> personMap = studentList.stream().collect(Collectors.toMap(s -> s.getId(), s -> s));
//按学生id抽取形成map集合,取第一个
Map<Long, Person> personMap = studentList.stream().collect(Collectors.toMap(s -> s.getId(), s -> s,(first,last)->first));
//按学生id抽取形成set集合
Set<Long> idSet = studentList.stream().map(s-> s.getId()).collect(Collectors.toSet());
分组
//按学生姓名分组
Map<String, List<Student>> map = students.stream().collect(Collectors.groupingBy(Student::getName));
//分组后保持有序
LinkedHashMap<String, ArrayList<Student>> collect = studentList.stream().collect(Collectors.groupingBy(Student::getName, LinkedHashMap::new, Collectors.toCollection(ArrayList::new)));
//按学生姓名分组,List存放学号
Map<String, List<Long>> map = students.stream().collect(Collectors.groupingBy(Student::getName, Collectors.mapping(Student::getId, Collectors.toList())));
//按学生姓名分组,Set存放学号
Map<String, Set<Long>> map = students.stream().collect(Collectors.groupingBy(Student::getName, Collectors.mapping(Student::getId, Collectors.toSet())));
计数
Map<String, Long> map = students.stream().collect(Collectors.groupingBy(Student::getName, Collectors.counting()));
最值
//最小
Integer min = studentList.stream().map(Student::getAge).min(Student::compareTo).get();
//最大
Integer max = studentList.stream().map(Student::getAge).max(Student::compareTo).get();
// 最大对象
User max = userList.stream().max(Comparator.comparing(Student::getAge)).get();
// 最小对象
User min = userList.stream().min(Comparator.comparing(Student::getAge)).get();
匹配
//查找list中是否都是张三
boolean result = studentList.stream().allMatch((s) -> s.getName().equals("张三"));
//查找list中是否有一个是张三
boolean result = studentList.stream().anyMatch((s) -> s.getName().equals("张三"));
//判断list中没有张三
boolean result = studentList.stream().noneMatch((s) -> s.getName().equals("张三"));
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/92447.html