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?
Comparatorfor theTypesenum already or not), but basically, if the comparison betweenTypesis0, then you compare theint, but you might need to apply some additional "weighting" to make it work just right