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

Html5 based widget for an iOS app: Today extension powered by the Ionic framework

At some point the thought of adding a Widget to my iOS app came to mind which was followed by starting work on adding a widget for my app, My Day Todos . Obviously the first step was to learn how to add a Widget to an iOS app and in that learning process I discovered many things about widgets in iOS first of which was a widget in iOS is a an app extension i.e a  Today Extension . While I am still haven't finished working on the widget for my iOS app, I thought I would take some time out and share what I have learned. In this post, I will share a few important tips and provide an example of how to add a Widget to an iOS app and have the widget UI powered by Html5 via  Ionic framework . I added some code to my Github repo, Html5StarterAppWithSwift in order to show how this can be achieved. There are already too many tutorials out on the Web on how to add a Today extension to an iOS app so I won't be including that here. Instead I will focus on sharing some of the useful tip...

Build a Full-Stack Image Upload App with Node.js, Express, React, and Vite (Beginner Tutorial)

 If you’re new to full-stack web development and want a hands-on project to practice React frontend integration with a Node.js + Express backend , this tutorial is for you. In this guide, we’ll walk through a simple but powerful app that lets users upload images, store them on the server, and display them back in the browser. This project is based on my GitHub repo: node-express-react-simple-fileupload . It’s designed to be beginner-friendly, SEO-optimized, and a great starting point for anyone learning JavaScript full-stack development . 🛠️ Technologies Used Here’s the tech stack powering this project: Node.js – JavaScript runtime for the backend. Express.js – Lightweight web framework for building REST APIs. Multer – Middleware for handling file uploads. CORS – Enables cross-origin requests between frontend and backend. React.js – Frontend library for building user interfaces. Vite – Fast development server and build tool for React. Fetch API – For making HTTP requests ...

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 ...