0

I have a list of objects that contains an enum field.

How can I sort it by the enum values alphabetically?

For example,

static enum Level { D, C, A, B } static class Item { Level level; public Item(Level level) { this.level = level; } } public static void main(String[] args) { Item item1 = new Item(Level.B); Item item2 = new Item(Level.A); Item item3 = new Item(Level.D); Item item4 = new Item(Level.C); List<Item> items = new ArrayList<>(List.of(item1, item2, item3, item4)); } 

I want the order to be A,B,C,D

2

1 Answer 1

6

name returns the name of the enum constants, so you can use that in Comparator.comparing:

items.sort(Comparator.comparing(item -> item.level.name())); 

After thinking about a bit further, I don't actually think this might not be a good design. If you do this, then you can't freely change your enum constant names, because that might also change the sort order. This is especially problematic if someone else who doesn't know that you are relying on enum names, reads your code and renames the constants for whatever reason (renaming normally won't break things if you use the IDE's rename tool), then your sorting code would sort them in a different order, which could potentially break many other things.

Sign up to request clarification or add additional context in comments.

1 Comment

@Elimination After thinking about a bit further, I don't actually think this might not be a good design. If you do this, then you can't freely change your enum constant names, because that might also change the sort order, and that might be unwanted. This is especially problematic if someone else who doesn't know that you are relying on enum names, reads your code and renames the constants for whatever reason, then your sorting code would sort them in a different order, which could break other things.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.