Skip to main content

Fun with sorting (Java)

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

Comments

Popular posts from this blog

Upload to AWS S3 from Java API

In this post, you will see code samples for how to upload a file to AWS S3 bucket from a Java Spring Boot app. The code you will see here is from one of my open-source repositories on Github, called document-sharing. Problem Let’s say you are building a document sharing app where you allow your users to upload the file to a public cloud solution. Now, let’s say you are building the API for your app with Spring Boot and you are using AWS S3 as your public cloud solution. How would you do that? This blog post contains the code that can help you achieve that. Read more below,  Upload to AWS S3 bucket from Java Spring Boot app - My Day To-Do (mydaytodo.com)

App update, discovering Protractor(testing) and an Angularjs State machine

So for the last couple of weeks, I have not be able to update my blog or finish a couple of the posts that I started writing. Well, I have...been a bit busy, with some the following things,  Testing my app I have been using the app( iOS ) on my iPhone for the past couple of months now, which is both good and bad. The good thing is I can test it and the bad thing is, I can use it every day. Part of the reason, I started building this app is to have something that I can and like to use everyday and since I am already using it, the incentive to release it is not as high as if it were something that I could not use. Anyway I did make some good progress over the last couple of weeks, like  Delete the app from my iPhone and do a clean install: this did help me find a few simple bugs that would pop-up when the app is first installed GET AN APP ICON, FINALLY! this was a bit of a hurdle and I thanks to Fiverr  and fivercrazyguy , I finally have my app icon. The day job ...

Why can't I cancel a local notification in my iOS app?(in Swift)

Prelude I have mentioned the fact that I am working on my first iOS app in a number of my previous posts and as such I face a number of newbie/noob(?) problems. They are not really problems as much as they are simply things that I do not know, for e.g. the following, how do I get the day of the week? where is my string.replaceAll in Swift? knowing which local notification brought my app to foreground ? serving HTML content in an iOS app that works on iOS 7 and above Thankfully, I have managed to make at least one generic solution and contribute it to the community i.e. my open-source Xcode project template( HTML5StarterAppWithSwift ) which you can get from Github . So this post basically describes another very simple problem that I have found a solution to, but I do not fully understand why the problem was occurring in the first place. Introduction As I have mentioned in this post , my iOS app uses local notifications i.e. UILocalNotification   and i...