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?
With some modifications, yes.
Add a constructor with an enum argument to define which field to use:
public class ItemComparator implements Comparator<Item>{
public enum Field {
ID, TIMESTAMP;
}
private Field field;
public ItemComparator(Field field) {
this.field = field;
}
Then in the compare method, switch on the field chosen:
@Override
public int compare(Item mdi1, Item mdi2) {
int comparison = 0;
switch(field) {
case TIMESTAMP:
comparison = mdi1.getTimestamp().compareTo(mdi2.getTimestamp());
case ID:
comparison = mdi1.getID() - mdi2.getID();
}
return comparison;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With