So every once in a while my boss makes an interesting sorting request, something like, i want the list of users sorted by locked, then production, then date joined and then name. Now sorting is generally a fun little problem in any capacity and some of the fancier requests from my boss make it even more interesting.

So as with most other things, even for sorting the general rule to only write something from scratch if there is absolutely nothing out there applies. I mean seriously even on those really boring days in the office where you are doing the most repetitive of tasks, it is generally a good idea to resist the urge to make things more interesting by writing something from scratch or worse configuring your servers to support Gopher.

Ok back to the point, so…..sorting in Java is pretty easy actually, all you need to do is call the Collections.Sort() method to a collection of objects that implement Comparable or better pass a specific Comparator. For those curious, the Collections.sort method uses a modified MergeSort algorithm under the covers, which is an O(n log n) algorithm.

For the purposes of this post i will only focus on sorting complex objects and not the simple cases such as sorting a list of integers.

So lets create a class called say

    public static class Person {
        public String name;
        public Integer age;
        public String address;

        public Person(String name, int age, String addr) {
            this.name = name;
            this.age = age;
            this.address = addr;
        }
    }So now there are 2 ways to sort an object of the class Person,

  1. Person can implement the Comparable interface, and you can define the compareTo method.
  2. Create a Comparator for the class Person and pass it to the Collections.sort method.

Often your sorting needs may go beyond your capability to implement Comparable for every class whose objects need to be sorted i.e. you may or may not be allowed to do so at work. So lets look at different scenarios of sorting using Comparators.

Case 1: Sort a List of Persons by name

        Comparator<Person> nameComparator = new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                // sort by the first name
                return p1.name.compareTo(p2.name);
            }
        };
        Collections.sort(persons, nameComparator );

and that should sort all persons by names in ascending order, if it needs to be descending just reverse the p1 with p2.

Case 2: Sort a List of Persons by name and age

So say we want to sort this such that if the name is equal we sort by the age. for this we will have to write a new Comparator .

       Comparator<Person> nameAndAgeComparator = new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                // sort by the first name, and if names are equal
                if (p1.name.compareTo(p2.name) == 0) {
                    return p1.age.compareTo(p2.age);
                } else {
                    return p1.name.compareTo(p2.name);
                }
            }
        };
        Collections.sort(persons, nameAndAgeComparator);

Case 3: Sorting a map based on its Keys (Person keys)

To have a map sorted by its keys, there are a bunch of options that include the use of a comparator in a TreeMap. So the TreeMap basically sorts the elements in a map based on its Natural ordering and the TreeMap also has a constructor which accepts a comparator and sorts each of the incoming elements.

So lets reuse the nameAndAgeComparator from the previous example to sort a map of Persons and some random value.

        Map<Person, String> sortedPersons = new TreeMap<Person, String(nameAndAgeComparator);
        Integer count = 0;
        Random rng = new Random(1);
        NumberFormat format = new DecimalFormat(“#.##”);
        for (Person person : persons) {
            Double randNo = rng.nextDouble();
            sortedPersons.put(person, format.format(randNo));
            count++;
        }
        for (Entry<Person, String> personEntry : sortedPersons.entrySet()) {
            print(“person id:” + personEntry.getKey().name.toString()  + “, Person Name:” + personEntry.getValue());
        }

So pretty simple isn’t it? You can access the full Java class for the above exap


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *