Java8 Stream()关于在所有用户的所有上传记录中,找出每个用户最新上传记录
原创文章:转载请标明出处 https://www.cnblogs.com/yunqing/p/9504196.html
首先分析相当于如下,在所有的猫中,每个名字的猫都保留年龄最小的一个
import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class test { public static void main(String[] args) { List<Cat> list = new ArrayList<>(); list.add(new Cat("小花",1,1)); list.add(new Cat("小花",2,1)); list.add(new Cat("小2",3,1)); list.add(new Cat("小2",4,1)); list.add(new Cat("小3",5,1)); list.add(new Cat("小3",7,1)); list.add(new Cat("小花",3,1)); list.add(new Cat("小1",1,1)); list.add(new Cat("小1",2,1)); list.add(new Cat("小1",3,1)); list.add(new Cat("小3",3,1)); list.add(new Cat("小3",12,1)); List<Cat> result = new LinkedList<>(); Map<String, List<Cat>> res = list.stream().collect(Collectors.groupingBy(Cat::getName)); Set<String> keys = res.keySet(); for (String str : keys) { List<Cat> groupList = list.stream().filter(e->e.getName().equals(str)).collect(Collectors.toList()); //以下两行都是找出组内年龄最小的猫 //Cat catMinAge0 = groupList.stream().reduce((one, two) -> one.getAge() < two.getAge() ? one : two).orElse(null); Cat catMinAge1 = groupList.stream().min(Comparator.comparingInt(o -> o.getAge())).orElse(null); result.add(catMinAge1); } System.out.println(result); } } class Cat{ private String name; private int age; private int gender; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public Cat() {} public Cat(String name, int age, int gender) { super(); this.name = name; this.age = age; this.gender = gender; } @Override public String toString() { return "Cat [name=" + name + ", age=" + age + ", gender=" + gender + "]"; } }
测试完毕,拿到项目中使用如下:
@Override @Transactional public List<DrivingRecord> findByCityCodeAndRecordTimeStartingWith(String cityCode, String recondTime) { //查询此区域今天所有用户的所有上报记录 List<DrivingRecord> list = drivingRecondDao.findByCityCodeAndRecordTimeStartingWith(cityCode, recondTime); List<DrivingRecord> resultList = new ArrayList<>(); //先根据用户分组,把同一个用户的上报记录放到同一个组 Map<User, List<DrivingRecord>> map = list.stream() .collect(Collectors.groupingBy(DrivingRecord::getUser)); //取出所有用户key值 Set<User> keys = map.keySet(); //遍历所有用户 for (User user : keys) { //找出与当前用户的分组 List<DrivingRecord> groupList = list.stream() .filter(u->u.getUser().equals(user)) .collect(Collectors.toList()); //比较时间,取当前用户的最新上报的记录 DrivingRecord dr = groupList.stream() .reduce((one,two)->one.getRecordTime().isBefore(two.getRecordTime())?two:one) .orElse(null); //把所有用户的最新上报信息填到resultList resultList.add(dr); } return resultList; }