1、分组
// 按年龄分组 ,多个分组
Map<Integer, List<Cat>> collect = catList.stream().collect(Collectors.groupingBy(Cat::getAge));
// 按性别分组, 两个分组
Map<Boolean, List<Cat>> collect = catList.stream().collect(Collectors.partitioningBy(c -> c.getSex().equals("公")));
1.1、分组统计个数:自定义key
2、最大值和最小值
Optional<Cat> max = catList.stream().max(Comparator.comparingInt(Cat::getAge));
Optional<Cat> min = catList.stream().min(Comparator.comparingInt(Cat::getAge));
3、属性值相累加
多个属性值累加
Semaphore semaphore = new Semaphore();
Optional<Semaphore> reduce = semaphores.stream().reduce((a, b) -> {
int accidentOri = a.getAccidentOri() + b.getAccidentOri();
int exceptionOri = a.getExceptionOri() + b.getExceptionOri();
a.setAccidentOri(accidentOri);
a.setExceptionOri(exceptionOri);
return a;
});
一个属性值累加
Long sumStream = userList.stream().mapToLong(User::getAge).sum();
分组统计累加
List<Semaphore> collect = new ArrayList<>(semaphores.stream().collect(Collectors.toMap(Semaphore::getVoltageId, a -> a, (o1, o2) -> {
o1.setAccidentOri(o1.getAccidentOri() + o2.getAccidentOri());
o1.setExceptionOri(o1.getExceptionOri() + o2.getExceptionOri());
// semaphore.setShiftOri(shiftOri);
o1.setNotifyOri(o1.getNotifyOri() + o2.getNotifyOri());
// semaphore.setLimitOri(limitOri);
o1.setTotalOri(o1.getTotalOri() + o2.getTotalOri());
o1.setAverageOri(o1.getAverageOri() + o2.getAverageOri());
o1.setAccidentReal(o1.getAccidentReal() + o2.getAccidentReal());
o1.setExceptionReal(o1.getExceptionReal() + o2.getExceptionReal());
// semaphore.setShiftReal(shiftReal);
o1.setNotifyReal(o1.getNotifyReal() + o2.getNotifyReal());
// semaphore.setLimitReal(limitReal);
o1.setTotalReal(o1.getTotalReal() + o2.getTotalReal());
o1.setAverageReal(o1.getAverageReal() + o2.getAverageReal());
return o1;
})).values());
3、排序
result = result.stream().sorted(new Comparator<SignalNoRest>() {
@Override
public int compare(SignalNoRest o1, SignalNoRest o2) {
return o1.getOccurTime().compareTo(o2.getOccurTime());
}
}).collect(Collectors.toList());
// 简化
result = result.stream().sorted(Comparator.comparing(SignalNoRest::getOccurTime)).collect(Collectors.toList());