I have a list of objects that I want to sort using different properties.
@Override
public int compareTo(Object obj)
{
Field tab = (Field) obj;
int objx = Integer.parseInt(tab.getX());
// int objy = Integer.parseInt(tab.getY());
int classX = Integer.parseInt(this.X);
if (classX == objx)
return 0;
else if (classX > objx)
return 1;
else
return -1;
}
What I have so far:
Collections.sort(list1); // But using property1 to sort
Collections.sort(list1); // But using property2 to sort
So, in first case I'm able to sort using property1, but how to sort using property2?
I'm trying to sort using different parameters, but compareTo()
accepts only one.
1. Creating Comparators for Multiple Fields. To sort on multiple fields, we must first create simple comparators for each field on which we want to sort the stream items. Then we chain these Comparator instances in the desired order to give GROUP BY effect on complete sorting behavior.
We can simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections. sort() method like below.
The sort method transfers control to the compare method, and compare method returns values based on the arguments passed: If both the objects are equal, returns 0. If the first object is greater than the second, returns a value > 0. If the second object is greater than the first, returns a value < 0.
To sort HashSet elements using Comparable interface in java first, we create a class Student that implements the Comparable interface. In this class we override the compareTo() method. And then we pass the set to the TreeSet constructor to sort the elements.
If you want to use two different property you need to use two different comparators.
A comparator is a class that implements the interface Comparator
public class EmpSort {
static final Comparator<Employee> comp1 = new Comparator<Employee>() {
public int compare(Employee e1, Employee e2) {
// use prperty1 to sort
return e2.hireDate().compareTo(e1.hireDate());
}
};
}
public class EmpSort2 {
static final Comparator<Employee> comp2 = new Comparator<Employee>() {
public int compare(Employee e1, Employee e2) {
// use prperty2 to sort
return e2.hireDate().compareTo(e1.hireDate());
}
};
}
Collections.sort(list1, comp1);//but using prperty1 to sort
Collections.sort(list1, comp2);//but using prperty2 to sort
One related question Collections sort(List<T>,Comparator<? super T>) method example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With