3

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?

4 Answers 4

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works, but it's probably preferable to have your enum extend Comparator<Item> directly and use a different Comparator for different cases, rather than hacking one Comparator to work differently in different cases.
2

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.