-3

I have List of object like,

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"));

I need to get the element from the object[] from the lowest date to highest date.

madhuri
  • 103
  • 2
  • 11

1 Answers1

0

Use Comparator for sorting it.

   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;
    }


}
Bishal Jaiswal
  • 1,684
  • 13
  • 15