0

so I am trying to sort an ArrayList as the title says. I have A Superclass called Thing that has 2 different subclasses, a HeavyThing and a LightThing. The ArrayList contains just the 2 subclasses and I need to sort it so the HeavyThing comes before the LightThing. So far I got the sort method to work for the name of the Things but I was unable to sort it by subclass.

        this.collThings.sort(new Comparator<Thing>() {
            public int compare(Thing t1, Thing t2) {
                return Integer.valueOf(t1.getName().compareTo(t2.getName()));
            }
        });

This is how I sorted it by name.

1 Answer 1

2

You can create a comparator chain and then as a first step compare the class' simple name. This will put HeavyThing before LightThing because in lexicographic order H comes before L. Then you can sub-sort by name:

this.collThings
    .sort(Comparator.comparing(t -> t.getClass().getSimpleName())
                    .thenComparing(Thing::getName));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this very useful, but I later down the line I have to sort the things by Date, Price etc. and I need to Sort the ArrayList just by telling if it is a heavy or a light thing.

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.