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?

Jon
  • 77
  • 1
  • 1
  • 8
  • 1
    [ArrayList.sort(Comparator super E> c)](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#sort-java.util.Comparator-) – Zachary Jan 31 '18 at 00: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. – hnefatl Jan 31 '18 at 00:53
  • Possible duplicate of [Sorting Java objects using multiple keys](https://stackoverflow.com/questions/8036429/sorting-java-objects-using-multiple-keys) – Mahendra Kapadne Jan 31 '18 at 01:17
  • The above stack overflow link gives you implementation of comparator which you are looking for. – Mahendra Kapadne Jan 31 '18 at 01:19

2 Answers2

1

Here is the java 8 way to do this.

arrayList.sort((a1, a2) -> a1.compareTo(a2));
user3298823
  • 302
  • 2
  • 17
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.

hnefatl
  • 5,860
  • 2
  • 27
  • 49