2

I am trying to order some arraylist from newest date to oldest date using comparator. But I can`t seem to get it right, the dates are getting sorted but not from newest to oldest.

Any help is appreciated.

Piece of the code involved:

public class MyFvModel {

    ...
    private long time;

    public MyFvModel(String fvName, long fvDate, long id) {
        this.fvName = fvName;
        this.fvDate = fvDate;
        this.id = id;
        this.time = System.currentTimeMillis();
    }

    public long getTime() {
        return time;
    }
    ...
    public static Comparator<MyFvModel> DateComparator = new Comparator<MyFvModel>() {

    public int compare(MyFvModel s1, MyFvModel s2) {
        long Date1 = s1.getFvDate();
        long curTime = s2.getTime();

        if (Date1 < curTime)
            return 0;
        else
            return 1;
        }
    };
}
Simon
  • 1,691
  • 2
  • 13
  • 28
  • 1
    did you have a look at the java doc for the [**compare**](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#compare-T-T-) method for when to return `-1`, `0` , `1`. – Ousmane D. Nov 25 '17 at 20:31
  • Maybe this can help https://stackoverflow.com/a/14050012/2940733 – Amin Mousavi Nov 25 '17 at 20:44

2 Answers2

0

You have to decide on which variable you want to order. If you want to order over you fvDate then your comparison should always compare s1.getFvDate() and s2.getFvDate() and not with other variables.

GVillani82
  • 17,196
  • 30
  • 105
  • 172
0

Your compare function is wrong. The compare function should return a negative number if s1 should came before s2, 0 if s1 and s2 are equal and a positive number if s1 should came after s2.

Since you want to return the newest to the oldest, you should return a negative number if s1 is newer than s2, 0 if is equal and a positive number if is older. Your fixed code is:

public int compare(MyFvModel s1, MyFvModel s2) {
    long date1 = s1.getFvDate();
    long date2 = s2.getFvDate();

    if (date1 > date2)
        return -1;
    else if(date1 < date2)
        return 1;
    else
        return 0;
};

A more simple version could be:

public int compare(MyFvModel s1, MyFvModel s2) {
    long date1 = s1.getFvDate();
    long date2 = s2.getFvDate();
    return date1 - date2;
}
jonathanrz
  • 4,206
  • 6
  • 35
  • 58