java—多个arraylist,按其中一个排序

cbwuti44  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(292)

这个问题在这里已经有答案了

我能把两张单子相对地排序吗(6个答案)
按日期属性排序对象列表(4个答案)
56分钟前关门了。

ArrayList<String> name = new ArrayList<>();
name.add("Adam");
name.add("Paul");
name.add("Ben");
ArrayList<String> hobby = new ArrayList<>();
hobby.add("Gardening");
hobby.add("Jogging");
hobby.add("Yoga");
ArrayList<String> dateLogin = new ArrayList<>();
dateLogin.add("2020-01-06");
dateLogin.add("2020-12-31");
dateLogin.add("2020-12-05");

有3组数据“亚当,园艺,2020-01-06”,“保罗,慢跑,2020-12-31”和“本,瑜伽,2020-12-05”。
如何按日期排序?

smtd7mpg

smtd7mpg1#

像我们的朋友在评论区告诉你的那样做。它可能看起来像:

public static void main (String [] args) {
        List<Member> members = new ArrayList<>();
        members.add(new Member("Adam", "Gardening", LocalDate.parse("2020-01-06")));
        members.add(new Member("Paul", "Jogging", LocalDate.parse("2020-12-31")));
        members.add(new Member("Ben", "Yoga", LocalDate.parse("2020-12-05")));

        Collections.sort(members);
        System.out.println(members);
    }

    private static class Member implements Comparable<Member> {
        private String name;
        private String hobby;
        private LocalDate dateLogin;

        public Member(String name, String hobby, LocalDate dateLogin) {
            this.name = name;
            this.hobby = hobby;
            this.dateLogin = dateLogin;
        }

        @Override
        public int compareTo(Member member) {
            //from newest to olders
            return member.dateLogin.compareTo(dateLogin);

            //or from oldest to newest
            //dateLogin.compareTo(member.dateLogin);
        }

        @Override
        public String toString() {
            return "Member{" +
                    "name='" + name + '\'' +
                    ", hobby='" + hobby + '\'' +
                    ", dateLogin=" + dateLogin +
                    '}';
        }

        //getters and setters...

    }

相关问题