2

I have an array filled with Integer objects that I'm looking to sort via the built-in ArrayList sort method. I'm not looking to do this via Collection.sort. Do I have to implement a comparator method to then pass to the sort method?

4
  • 1
    ArrayList.sort(Comparator<? super E> c) Commented Jan 31, 2018 at 0:52
  • 1
    The relevant part of the link that Zachary posted is "A null value indicates that the elements' natural ordering should be used" - so just pass it null instead of a comparator, and it'll sort integers by their default ordering. Commented Jan 31, 2018 at 0:53
  • Possible duplicate of Sorting Java objects using multiple keys Commented Jan 31, 2018 at 1:17
  • The above stack overflow link gives you implementation of comparator which you are looking for. Commented Jan 31, 2018 at 1:19

2 Answers 2

1

Here is the java 8 way to do this.

arrayList.sort((a1, a2) -> a1.compareTo(a2));
Sign up to request clarification or add additional context in comments.

Comments

1

The ArrayList.sort method does take a comparator which can be used to specify the sorting criteria, but as mentioned on the documentation page, passing it a null comparator is also valid:

If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements' natural ordering should be used.

And as you can see from the Integer documentation, Integer implements Comparable<Integer>, so it has a natural ordering.


So to sort your ArrayList<Integer> you can just do:

ArrayList<Integer> arr = new ArrayList<>();
...
arr.sort(null); // Null comparator forces sort by natural ordering

Demo here.

Comments

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.