stream流根据时间筛选list最新数据

public static void main(String[] args) throws ParseException {
        List<Student> list = new ArrayList<>();
        list.add(new Student("zhangsan",10,TimeUtils.stringToDate("2022-07-07 22:20:41")));
        list.add(new Student("zhangsan",30,TimeUtils.stringToDate("2022-07-07 22:20:43")));
        list.add(new Student("zhangsan",20,TimeUtils.stringToDate("2022-07-07 22:20:42")));
        list.add(new Student("zhangsan",40,TimeUtils.stringToDate("2022-07-07 22:20:46")));
        list.add(new Student("lisi",30,TimeUtils.stringToDate("2022-07-07 22:20:43")));

        Map<String, List<Student>> map = list.stream().collect(Collectors.groupingBy(Student::getName));
        map.keySet().forEach(key -> {
            List<Student> students = map.get(key);
            //int maxAge = l.stream().map(s -> s.getAge()).mapToInt(Integer::intValue).max().getAsInt();
            List<Date> dateList = students.stream().map(Student::getBirth).collect(Collectors.toList());
            Date date = dateList.stream().max(Date::compareTo).get();
            List<Student> maxAgeStu = students.stream().filter(s -> s.getBirth().getTime() == date.getTime()).collect(Collectors.toList());
            System.out.println(maxAgeStu);
        });
    }
    /*public static void main(String[] args) throws ParseException {
        List list = new ArrayList<>();
        list.add(new Student("zhangsan",10,TimeUtils.stringToDate("2022-07-07 22:20:41")));
        list.add(new Student("zhangsan",30,TimeUtils.stringToDate("2022-07-07 22:20:43")));
        list.add(new Student("zhangsan",20,TimeUtils.stringToDate("2022-07-07 22:20:42")));
        list.add(new Student("lisi",30,TimeUtils.stringToDate("2022-07-07 22:20:43")));
        Map> collect = list.stream().collect(Collectors.groupingBy(Student::getName));
        collect.keySet().forEach(key->{
            List students = collect.get(key);
            List collect1 = students.stream().sorted(new Comparator() {
                @Override
                public int compare(Student o1, Student o2) {
                    long time = o1.getBirth().getTime();
                    long time1 = o2.getBirth().getTime();
                    if (time>time1) {
                        return 1;
                    }
                    return -1;
                }
            }).collect(Collectors.toList());
            Date birthday = collect1.get(collect1.size()-1).getBirth();
            List maxAgeStu = students.stream().filter(
                    s -> s.getBirth().getTime()==birthday.getTime()).collect(Collectors.toList());
            System.out.println(maxAgeStu);
        });
    }*/

实体类

/**
 * @author およそ神
 * @version JDK 1.8
 */
@Data
public class Student {
    String name;
    Integer age;
    Date birth;

    public Student(String name, Integer age,Date birth) {
        this.name = name;
        this.age = age;
        this.birth = birth;
    }
}

你可能感兴趣的:(Java,算法,经验知识,list,java,数据结构)