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. Sorting is generally a fun problem and some of the fancier requests from my boss make it even more interesting. Since I work with Java, let’s see how we do sorting in Java. 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?

Get updates?

If you find any of my posts useful and want to support me, you can buy me a coffee :)

https://www.buymeacoffee.com/bhumansoni

Or you can  buying or even try one of my apps on the App Store. 

https://mydaytodo.com/apps/

In addition the above, have a look at a few of the other posts,
How to create radio buttons using vanilla Javascript
https://mydaytodo.com/vanilla-javascript-create-radio-buttons/

How to build a Javascript frontend for Java Spring Boot backend 
https://mydaytodo.com/java-spring-boot-vanilla-javascript-solution/

Or have a look at some useful Javascript tutorials below
https://mydaytodo.com/category/javascript/
Categories: Java

0 Comments

Leave a Reply

Avatar placeholder