【问题标题】:Get the element from List<Object> based on date [duplicate]根据日期从 List<Object> 获取元素 [重复]
【发布时间】:2019-04-19 13:39:19
【问题描述】:

我有类似的对象列表,

List<Student> list = new ArrayList<Student>();

list.add(new Student("abc","2019-02-01"));
list.add(new Student("bcd","2019-02-01"));
list.add(new Student("cdf","2019-02-01"));
list.add(new Student("fgh","2019-02-01"));
list.add(new Student("abc","2019-02-02"));
list.add(new Student("bcd","2019-02-02"));
list.add(new Student("cdf","2019-02-02"));
list.add(new Student("fgh","2019-02-02"));

我需要从 object[] 中获取从最低日期到最高日期的元素。

【问题讨论】:

  • 在发布之前始终彻底搜索 Stack Overflow。

标签: java arrays sorting date


【解决方案1】:

使用Comparator 对其进行排序。

   public class st {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<Student>();

        list.add(new Student("abc", "2019-02-01"));
        list.add(new Student("bcd", "2019-02-01"));
        list.add(new Student("cdf", "2019-02-01"));
        list.add(new Student("fgh", "2019-02-01"));
        list.add(new Student("abc", "2019-02-02"));
        list.add(new Student("bcd", "2019-02-02"));
        list.add(new Student("cdf", "2019-02-02"));
        list.add(new Student("fgh", "2019-02-02"));
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object arg0, Object arg1) {
                if (!(arg0 instanceof Student)) {
                    return -1;
                }
                if (!(arg1 instanceof Student)) {
                    return -1;
                }

                Student st0 = (Student)arg0;
                Student st1 = (Student)arg1;


                try {
                    Date one = new SimpleDateFormat("yyyy-MM-dd").parse(st0.getDate());
                    Date two =  new SimpleDateFormat("yyyy-MM-dd").parse(st1.getDate());
                    return one.after(two)? 1:-1;
                } catch (ParseException e) {
                    return -1;
                }
            }
        });

        for(Student s: list) {
            System.out.println(s.getDate());
        }
    }
}

class Student{
    private String name;
    private String date;
    public Student(String name, String date) {
        super();
        this.name = name;
        this.date = date;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }


}

【讨论】:

  • 谢谢,有没有不使用comarator 对列表进行排序的方法。
  • 是的,你可以使用 lamda 表达式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
相关资源
最近更新 更多