Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some method in the Java standard library to get the smallest enum out of a set of enums?

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.

like image 446
soc Avatar asked Jan 18 '23 19:01

soc


2 Answers

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.

like image 166
maasg Avatar answered Jan 30 '23 08:01

maasg


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

like image 35
Kevin Bourrillion Avatar answered Jan 30 '23 08:01

Kevin Bourrillion