janenz00
janenz00

Reputation: 3310

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?

Upvotes: 3

Views: 5821

Answers (4)

camickr
camickr

Reputation: 324118

You can use the Bean Comparator. Then you can sort on any property in your class. You just specify the method name you want to use to get the property to sort. For example:

BeanComparator byId = new BeanComparator(Item.class, "getId");
Collections.sort(items, byId);

This comparator can be used on any class.

Upvotes: 1

rgettman
rgettman

Reputation: 178263

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;
}

Upvotes: 3

Jonathan Rosenne
Jonathan Rosenne

Reputation: 2217

Use two separate comparators. Select which one you want to use in the sort call.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500675

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...

Upvotes: 2

Related Questions