Search code examples
javajspenumset

How to display EnumSet in JSP file in custom order?


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?


Solution

  • 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