How to sort a list of Strings or Integers in Java
Following on from our introduction to sorting in Java, we consider here one of the simplest cases of sorting a List of simple objects such as Strings or Integers. Let's say we have a simple list of Strings:
List<String> words = new ArrayList<String>(50); words.add("once"); words.add("upon"); words.add("a"); words.add("time"); ...
Now, we can sort this list with a simple call to the following library method:
The Collections.sort() method will work "out of the can" on lists of various "basic" objects that you'd expect to be able to sort, including instances of Number– the primitive wrapper classes Integer, Long, Float etc plus BigInteger and BigDecimal.
Sorting an array
Sorting an array of these objects is just as easy1:
The above method takes an array of objects, but the Arrays class also provides similar methods for sorting primitive arrays.
Next: other issues
What we've seen above is that sorting simple objects in Java such as numbers or strings is generally dead simple. But there are a couple more issues to deal with on the following pages:
1. In fact, the Collections.sort() method copies the list into an array and calls the Arrays.sort() method before copying the elements back into the list.
Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved. If you have any feedback on the Java collections tutorials in this section or about the content of this site in general, please leave a message on the Javamex forum.