Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java custom comparator with different sort options

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?

like image 458
janenz00 Avatar asked Mar 03 '26 11:03

janenz00


1 Answers

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;
}
like image 54
rgettman Avatar answered Mar 06 '26 01:03

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!