【java】lambda表达式之List操作

【java】lambda表达式之List操作

  • 【java】lambda表达式之List操作
    • 去重
    • 过滤
    • 抽取
    • 分组
    • 计数
    • 最值
    • 匹配
    • 求和

【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("张三"));

求和

Integer ageSum = studentList.stream().mapToInt(Student::getAge).sum();

你可能感兴趣的:(java,lambda,java)