I have a an Item class with two properties - id and timestamp. There is a custom comparator class to sort an itemList according to the timestamp.
Is there a way to use the comparator class such that I can specify sort by timestamp or sort by id?
Item class:
public class Item {
private Integer id;
private Date timestamp;
}
Comparator :
public class ItemComparator implements Comparator<Item>{
@Override
public int compare(Item mdi1, Item mdi2) {
return mdi1.getTimestamp().compareTo(mdi2.getTimestamp());
}
}
Sort code:
Collections.sort(itemList, new ItemComparator());
Can I use the same comparator to sort the list by Id too?
Can I use the same comparator to sort the list by Id too?
Well you could have a constructor parameter to say which property you want to sort by - but personally I'd create a different class for that instead. You can have as many classes implementing Comparator<Item>
as you like...
See more on this question at Stackoverflow