0

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?

1
  • A lot will come down to how re-usable a solution you want (ie, if you have a Comparator for the Types enum already or not), but basically, if the comparison between Types is 0, then you compare the int, but you might need to apply some additional "weighting" to make it work just right Commented Jan 25, 2016 at 22:17

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You might have to add some extra type parameters like this: Comparator<TestClass> comparator = Comparator.<TestClass, Types>comparing(x -> x.types).thenComparing(x -> x.num)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.