0

I have an java.util.EnumSet containing a lot of elements that is being displayed as a drop down list (JSP). Now, by default they're sorted by ID:

1 Toyota
2 Honda
3 Audi
4 BMW 

What I want to achieve is the list in alphabetic order:

3 Audi
4 BMW
2 Honda
1 Toyota

Can I change the order of displaying the enums on the drop down list without changing their IDs?

pidabrow
  • 966
  • 1
  • 21
  • 47
  • 1
    Yes. Copy the elements to a list, and sort the list the way you want to. Iterate through the list to generate the options of the dropdown. Note that enums don't have an ID. They have a name, and an ordinal. Their natural order is the order of their ordinal. – JB Nizet Mar 31 '17 at 12:56

1 Answers1

2

You can create an ordered Collection from the EnumSet and then use that in JSP. However then you won't be getting benefits of EnumSet, in that case there's no need to use it in the first place.

Check following sample for creating desired ordered List

import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;

public class TestEnumSet {
    public static void main(String[] args) {
        System.out.println("Started\n");

        EnumSet<Cars> set = EnumSet.of(Cars.Toyata, Cars.Audi, Cars.Honda, Cars.BMW);

        List<Cars> list = Arrays.asList(set.toArray(new Cars[]{}));
        list.sort((a, b) -> a.toString().compareTo(b.toString()));

        list.stream().forEach(a -> System.out.println(a.id + " : " + a.toString()));

        System.out.println("\nFnished");
    }

    public static enum Cars {
        Toyata(1), Audi(2), Honda(3), BMW(4);

        int id;
        Cars(int id ) {
            this.id = id;
        }
    }
}

Output

Started

2 : Audi
4 : BMW
3 : Honda
1 : Toyata

Fnished
11thdimension
  • 10,333
  • 4
  • 33
  • 71
  • 1
    Since you're using streams, you could create a sorted list in one step using `set.stream().sorted(Comparator.comparing(Object::toString)).collect(Collectors.toList())` – JB Nizet Mar 31 '17 at 17:29
  • There's a weird compilation error coming using `set.stream()...`, `The method t‌​oList() is undefined for the type Collectors` – 11thdimension Mar 31 '17 at 17:58