Consider a collection consisting of enum types. Is there some library method min
(or max
) which accepts this collection (or varargs) and returns the smallest/highest value?
EDIT: I meant the natural order of enums, as defined by their compare
implementation of Comparable
.
Enums implement Comparable<E>
(where E is Enum<E>
) and their natural order is the order in which the enum constants are declared.
You can use their default Comparable implementation to get the max and min constants as declared:
public enum BigCountries {
USA(312), INDIA(1210), CHINA(1330), BRAZIL (190);
private int population;
private BigCountries(int population) {
this.population = population;
}
}
Then you can use:
BigCountries first = Collections.min(Arrays.asList(BigCountries.values())); // USA
BigCountries last = Collections.max(Arrays.asList(BigCountries.values())); //BRAZIL
Probably, a faster way would be to use direct access to the array returned by the values()
method:
BigCountries[] values = BigCountries.values();
System.out.println(values[0]); // USA;
System.out.println(values[values.length-1]); // BRAZIL;
Note that the parameter given to the enum has no effect in the ordering.
If you have some Set<MyEnum>
, it should already be of type EnumSet
. Sadly, this class does not provide first
and last
methods, but it does guarantee to iterate in increasing order, so you can reliably use, for example, the first and last elements in thatSet.toArray()
.
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