1

I have a List of obejcts which looks like this:

List<MyObject> myObjects = ...

and MyObject has a reference to another object MyReferencedObject. I will sort List myObjects concerning a field of MyReferencedObject called sortOrder (Integer). Is there a performant possibility to do this in a performant way?

1 Answer 1

1

You can either make it implement Comparable (especially if such comparison is not one-off and will be reused).

Then just call:

Collections.sort(myObjects);

Or define the order using a lambda expression:

Collections.sort(myObjects, (o1, o2) ->
      o1.getReferencedObject().getSortOrder()
      .compareTo(o2.getReferencedObject().getSortOrder()));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, the second solution works for me (MyObject is compareable by another field). Thanks!
You can also use Comparator::comparing to derive a Comparator from a getter Function: Collections.sort(myObjects, Comparator.comparing(o -> o.getReferencedObject().getSortOrder()));

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.