Doejbn
Doejbn

Reputation: 13

Sorting by enum and integer in an object in a list in Java?

I have this class and enum in my program (names changed and simplified):

public enum Types {
    FIRST, SECOND, THIRD
}
public class TestClass {
    Types types;
    int num;
    public TestClass(Types types, int num) {
        this.types = types;
        this.num = num;
}

Now let's say I have TestClass objects in an ArrayList like this:

ArrayList<TestClass> list = new ArrayList<>();
list.add(new TestClass(Types.THIRD, 2);
list.add(new TestClass(Types.THIRD, 1);
list.add(new TestClass(Types.FIRST, 3);
list.add(new TestClass(Types.FIRST, 1);
list.add(new TestClass(Types.FIRST, 2);

I would like to sort the list first based on the enums and then based on the num, so that the end result would be this:

[(Types.FIRST, 1), (Types.FIRST, 2), (Types.FIRST, 3), (Types.THIRD, 1), (Types.THIRD, 2)] 

I see that I could use Comparator, but I'm unsure exactly how I could sort by enums and then by numbers inside the enums. Two comparators? Nested comparators? What would be the optimal solution for this?

Upvotes: 0

Views: 273

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198153

Are you using Java 8? If so, you can write

Comparator<TestClass> comparator = 
   comparing(tc -> tc.types)
      .thenComparingInt(tc -> tc.num);

...and then you could write

list.sort(comparator);

Upvotes: 3

Related Questions