遍历

  1. for (Entry<String, String> entry: map.entrySet()) {
  2. key = entry.getKey();
  3. value = entry.getValue();
  4. }

排序

  1. List<StudentInfo> studentList = new ArrayList<>();
  2. studentList.add(new StudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23)));
  3. studentList.add(new StudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3)));
  4. studentList.add(new StudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11)));
  5. studentList.add(new StudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18)));
  6. // 按【年龄】升序排序 (Integer类型)
  7. List<StudentInfo> studentsSortName = studentList.stream()
  8. .sorted(Comparator.comparing(StudentInfo::getAge))
  9. .collect(Collectors.toList());
  10. //按【年龄】降序排序 (Integer类型)
  11. List<StudentInfo> studentsSortName2 = studentList.stream()
  12. .sorted(Comparator.comparing(StudentInfo::getAge).reversed())
  13. .collect(Collectors.toList());
  14. // 先按【年龄】降序排序,再按【身高】升序排序 (Integer类型)
  15. List<StudentInfo> studentsSortName = studentList.stream()
  16. .sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight))
  17. .collect(Collectors.toList());

分组

  1. // 分组
  2. Map<String, List<Employee>> map = employees.stream()
  3. .collect(Collectors.groupingBy(Employee::getCity))
  4. // 分组计数
  5. Map<String, Long> map = employees.stream()
  6. .collect(Collectors.groupingBy(Employee::getCity, Collectors.counting()));
  7. // 分组求平均值
  8. Map<String, Double> map = employees.stream()
  9. .collect(Collectors.groupingBy(Employee::getCity, Collectors.averagingInt(Employee::getAge)));
  10. // 分组求和
  11. Map<String, Long> map = employees.stream()
  12. .collect(Collectors.groupingBy(Employee::getCity, Collectors.summingLong(Employee::getAmount)));
  13. // 分组-选字段输出
  14. Map<String, Set<String>> map = employees.stream().collect(
  15. Collectors.groupingBy(Employee::getCity, Collectors.mapping(Employee::getName, Collectors.toSet())));

BigDecimal 分组求和

  1. Map<String, BigDecimal> dSumQtyMap = allDetails.stream()
  2. .collect(Collectors.toMap(Detail::getSrcDetailId, Detail::getQty, BigDecimal::add));
  3. list.stream()
  4. .map(e->e.getValue())
  5. .reduce(BigDecimal.ZERO, BigDecimal::add);

重复元素

  1. List<User> users = new ArrayList<>();
  2. users.add(new User("xpf1","1238",18));
  3. users.add(new User("xpf2","1234",18));
  4. users.add(new User("xpf3","1235",18));
  5. users.add(new User("xpf","1236",18));
  6. users.add(new User("xpf","1237",18));
  7. Map<String, Long> collect = users
  8. .stream()
  9. .map(User::getUserName)
  10. .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
  11. List<String> result = new ArrayList<>();
  12. collect.forEach((k,v)->{
  13. if(v>1)
  14. result.add(k);
  15. });
  16. System.out.println(result.toString());