Sorting an Array

From Progzoo
Jump to: navigation, search

You can sort an array in Java with java.util.Arrays.sort

Sort an array

The static method java.util.Arrays.sort can be used if the sort is simple:

Sort the list 2,7,5,4.


[Font] [Default] [Show] [Resize] [History] [Profile]

Sort an array using a custom comparator

You can create your own comparator. This means that you decide how the sort is to be done. You must implement the compare method - this returns a negative, zero or a positive integer depending on how o1 compares to o2.

return -1 (or any negative number) if o1 comes before o2
return  0 if o1 and o2 are the same
return  1 (or any positive number) if o1 comes after o2


[Font] [Default] [Show] [Resize] [History] [Profile]

Sort an array using an anonymous custom comparator

This is essentially the same as the above - but you do not need to explicitly name the comparator.


[Font] [Default] [Show] [Resize] [History] [Profile]


Sort an ArrayList

For an ArrayList (or any List) you use Collections.sort


[Font] [Default] [Show] [Resize] [History] [Profile]

Sort an ArrayList using a Custom Comparator

In this example you can sort an ArrayList of List. Notice that the output is ordered by region:

[[Angola, Africa, 1250000, 14500000, 14935000000],
 [Benin, Africa, 112622, 7100000, 3763000000],
 [Botswana, Africa, 581730, 1800000, 7812000000],
 ...


[Font] [Default] [Show] [Resize] [History] [Profile]