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)

Addressing app review rejections for auto-renewing subscription in-app purchase (iOS)

The ability to know what the weather is like while planning your day is a feature of  My Day To-Do  Pro and as of the last update it’s also a part of the  Lite version . Unlike the Pro version it’s an auto-renewing subscription based  in-app purchase (IAP)  in the Lite version. What means is that when a user purchases it, the user only pays for the subscription duration after which the user will be automatically charged for the next period. Adding an  auto-renewing  subscription based IAP proved to be somewhat challenging in terms of the app store review i.e. the app update was rejected by the App Review team thrice because of missing information about the IAP. Therefore in this post I will share my experiences and knowledge of adding auto-renewing IAP in hopes to save someone else the time that I had to spend on this problem. In-App purchase This year I started adding IAPs to My Day To-Do Lite which lead to learning about different types of IAP...

Serving HTML content in an iOS app that works in iOS 7 and later (using Swift)

As I have mentioned in an earlier post , I really enjoying coding in Swift. Now what am I doing with it? Well I am trying to build an HTML5 app that must work on devices with iOS 7. So in iOS8 apple has introduced a whole bunch of features that facilitate easy communication between web content and lets just call it back-end Swift code, but those features are not in iOS 7. So why do I want to build something that would work in an older OS? well I do not expect existing iOS users to upgrade to iOS 8 straight away and i also know a couple of people who would be very reluctant to upgrade their iPhones to iOS 8. Now in case you do not, you can have a read of the "Working with WebViews" section of this post , to know how to serve HTML content with WebViews. So when I started building my app, I wanted to know: How do I invoke some Swift code from my HTML content? Well the solution to this may feel a little bit "hacky" but it is a solution to achieve this.  The followi...