Is there any method in the standard Java library for getting the smallest enumeration from a set of enums?

Consider a collection of enumeration types. Is there any library min (or max ) method that takes this collection (or varargs) and returns the smallest / largest value?

EDIT: I was referring to the natural order of enums, as determined by their implementation of compare Comparable .

+4
source share
3 answers

Enums implement Comparable<E> (where E is Enum<E> ), and their natural order is the order in which enumeration constants are declared. You can use your default Comparable implementation to get the max and min constants as announced:

 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 assigned to the enumeration does not affect the order.

+6
source

If you have Set<MyEnum> , it should already be of type EnumSet . Unfortunately, this class does not provide first and last methods, but it guarantees iteration in ascending order, so you can reliably use, for example, the first and last elements in thatSet.toArray() .

+2
source

If you need a custom order (e.g. alphabetically), use an arbitrary comparator in any collection

 class MyComparator implements Comparator<MyEnumType> { public int compare(MyEnumType enum1, MyEnumType enum2) { return o1.toString().compareTo(o1.toString()); } } 

If you want to keep the declared order, put them in a SortedSet

 SortedSet<MyEnumType> set = new TreeSet<MyEnumType>(); set.add(enum1); 
+1
source

All Articles