Quantcast
Channel: How to sort a list of objects - Stack Overflow
Viewing all articles
Browse latest Browse all 7

How to sort a list of objects

$
0
0

Supposing that I have a list of Test as below:

    public class Test {    public static enum Unit {        DAY, WEEK, MONTH, YEAR /* , DAY_TO_DAY */    }    private int value;    private Unit unit;    public int getValue() {        return value;    }    public void setValue(int value) {        this.value = value;    }    public Unit getUnit() {        return unit;    }    public void setUnit(Unit unit) {        this.unit = unit;    }}

I will have a list of Test with the below values :

3 day, 5 month, 5 day, 6 year, 6 week, 12 week,

and our expection result as below :

3 day, 5 day, 6 week , 12 week, 5 month, 6 year

Currently, I create a code as below

Collections.sort(tests, new Comparator<Test >() {  @Override  public int compare(Test o1, Test o2) {    if(o1.getValue() > o2.getValue()) return 1;    if(o1.getValue() < o2.getValue()) return -1;    return 0;  }

However, it only sort by value and not by Unit.The result with the above implementation is :

3 day, 5 day, 5 month, 6 week , 6 year, 12 week.

Please tell me know the way to satisfy two conditions (Unit and values) in this case.Thanks.


Viewing all articles
Browse latest Browse all 7

Latest Images

Trending Articles





Latest Images