1、分组

  1. // 按年龄分组 ,多个分组
  2. Map<Integer, List<Cat>> collect = catList.stream().collect(Collectors.groupingBy(Cat::getAge));
  3. // 按性别分组, 两个分组
  4. Map<Boolean, List<Cat>> collect = catList.stream().collect(Collectors.partitioningBy(c -> c.getSex().equals("公")));

1.1、分组统计个数:自定义key

image.png

2、最大值和最小值

  1. Optional<Cat> max = catList.stream().max(Comparator.comparingInt(Cat::getAge));
  2. Optional<Cat> min = catList.stream().min(Comparator.comparingInt(Cat::getAge));

3、属性值相累加

多个属性值累加

  1. Semaphore semaphore = new Semaphore();
  2. Optional<Semaphore> reduce = semaphores.stream().reduce((a, b) -> {
  3. int accidentOri = a.getAccidentOri() + b.getAccidentOri();
  4. int exceptionOri = a.getExceptionOri() + b.getExceptionOri();
  5. a.setAccidentOri(accidentOri);
  6. a.setExceptionOri(exceptionOri);
  7. return a;
  8. });

一个属性值累加

  1. Long sumStream = userList.stream().mapToLong(User::getAge).sum();

分组统计累加

  1. List<Semaphore> collect = new ArrayList<>(semaphores.stream().collect(Collectors.toMap(Semaphore::getVoltageId, a -> a, (o1, o2) -> {
  2. o1.setAccidentOri(o1.getAccidentOri() + o2.getAccidentOri());
  3. o1.setExceptionOri(o1.getExceptionOri() + o2.getExceptionOri());
  4. // semaphore.setShiftOri(shiftOri);
  5. o1.setNotifyOri(o1.getNotifyOri() + o2.getNotifyOri());
  6. // semaphore.setLimitOri(limitOri);
  7. o1.setTotalOri(o1.getTotalOri() + o2.getTotalOri());
  8. o1.setAverageOri(o1.getAverageOri() + o2.getAverageOri());
  9. o1.setAccidentReal(o1.getAccidentReal() + o2.getAccidentReal());
  10. o1.setExceptionReal(o1.getExceptionReal() + o2.getExceptionReal());
  11. // semaphore.setShiftReal(shiftReal);
  12. o1.setNotifyReal(o1.getNotifyReal() + o2.getNotifyReal());
  13. // semaphore.setLimitReal(limitReal);
  14. o1.setTotalReal(o1.getTotalReal() + o2.getTotalReal());
  15. o1.setAverageReal(o1.getAverageReal() + o2.getAverageReal());
  16. return o1;
  17. })).values());

3、排序

  1. result = result.stream().sorted(new Comparator<SignalNoRest>() {
  2. @Override
  3. public int compare(SignalNoRest o1, SignalNoRest o2) {
  4. return o1.getOccurTime().compareTo(o2.getOccurTime());
  5. }
  6. }).collect(Collectors.toList());
  7. // 简化
  8. result = result.stream().sorted(Comparator.comparing(SignalNoRest::getOccurTime)).collect(Collectors.toList());