How would you sort a collection of data based on two properties of an entity in Java, analogical to SQL’s Order by firstField, SecondField desc?

By | March 5, 2023

In Java, you can sort a collection of data based on two properties of an entity using the Comparator interface. The Comparator interface provides a way to compare two objects and determine their relative ordering. Here’s an example code snippet that demonstrates how to sort a collection of data based on two properties of an entity:

import java.util.*;

public class EntitySorter {
public static void main(String[] args) {
List<Entity> entities = new ArrayList<>();
entities.add(new Entity(“John”, “Doe”, 30));
entities.add(new Entity(“Alice”, “Smith”, 25));
entities.add(new Entity(“Bob”, “Johnson”, 35));
entities.add(new Entity(“Alice”, “Jones”, 27));
entities.add(new Entity(“Bob”, “Brown”, 32));

Comparator<Entity> comparator = Comparator.comparing(Entity::getFirstField)
.thenComparing(Comparator.comparing(Entity::getSecondField).reversed());

Collections.sort(entities, comparator);

entities.forEach(System.out::println);
}
}

class Entity {
private String firstField;
private String secondField;
private int age;

public Entity(String firstField, String secondField, int age) {
this.firstField = firstField;
this.secondField = secondField;
this.age = age;
}

public String getFirstField() {
return firstField;
}

public String getSecondField() {
return secondField;
}

public int getAge() {
return age;
}

@Override
public String toString() {
return “Entity{” +
“firstField='” + firstField + ‘\” +
“, secondField='” + secondField + ‘\” +
“, age=” + age +
‘}’;
}
}

In this example, we have a collection of Entity objects, each with two fields firstField and secondField, and an age field. We create a Comparator object that first sorts based on the firstField property, and then sorts based on the secondField property in descending order. Finally, we use the Collections.sort() method to sort the entities list based on the Comparator, and then print out the sorted list using the forEach() method.

The resulting output will be:

Entity{firstField=’Alice’, secondField=’Jones’, age=27}
Entity{firstField=’Alice’, secondField=’Smith’, age=25}
Entity{firstField=’Bob’, secondField=’Brown’, age=32}
Entity{firstField=’Bob’, secondField=’Johnson’, age=35}
Entity{firstField=’John’, secondField=’Doe’, age=30}

As you can see, the list is sorted first by the firstField property in ascending order, and then by the secondField property in descending order.

Leave a Reply

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