0

Let's say Enum MyClass { ORANGE, APPLE, BANANA; }

In this case this will be true: ORANGE.compareTo(APPLE)<0 and Collections.min() would give me ORANGE

If I have private static final String[] values = {ORANGE, APPLE, BANANA};

Is there a way to return same result. I tried using Collections.min(values), but the answer was APPLE, because it was using natural order.

I tried using this public static <T> T min(Collection<? extends T> coll,Comparator<? super T> comp) so that it returns the minimum element of the given collection, according to the order induced by the specified comparator. If I want to have above result, how do I define the Comparator?

  • 2
    If your array is already sorted then just use `values[0]`? I don't understand what the problem is here. – Amongalen Sep 30 '20 at 07:38
  • 1
    I'm only guessing that you want to sort one collection based on an order of some other. If that is the case, check this question: https://stackoverflow.com/questions/18129807/in-java-how-do-you-sort-one-list-based-on-another – Amongalen Sep 30 '20 at 07:44
  • What you are actually comparing, whencomparing items of an enum, is not their String value, but their enum ordinal, which is assigned by the order, of the items in the enum. For an easier way of comparing it you could just get the corresponding ordinal from the enum by calling `MyClass.valueof(someString).ordinal()` and compare that in your comparator. – Amir Schnell Sep 30 '20 at 08:07
  • @AmirSchnell check [this thread](https://stackoverflow.com/questions/44654291/is-it-good-practice-to-use-ordinal-of-enum). It's not a good practice to use ordinals... – dbl Sep 30 '20 at 09:03

0 Answers0