Java – provides multiple types of sorting for objects
Suppose I have a Java object with multiple string fields
public class Person {
private String field1
// keeps going
I want to be able to sort the list of people according to any field I choose
I know that I can use the comparator interface and implement multiple comparetos, such as the topic: how do I make 2 comparable methods in only one class? As described in
But when using collections When sort()
But without all this repetitive code, is there any way I can do this?
Solution
@JB nizet's Java 8 solution will be a trick, but it only applies to Java 8 What is the version below 8 that most people use?
I will provide you with a simple solution that I think is lower than Java 8
You really don't need to create multiple comparator classes (you call them "duplicate code") How to use appropriate techniques, such as conditions or enumerations?
private Comparator<YourClass> getComparator(MyPropertiesEnum myEnum) {
return new Comparator<YourClass>() {
@Override
public int compare(YourClass o1,YourClass o2) { {
switch (myEnum) {
case FIRSTNAME:
// implementation for firstname
break;
case LASTNAME:
// implementation for lastname
break;
default:
// implementation for default version
break;
}
}
};
}
The location of mypropertiesenum is as follows:
public enum MyPropertiesEnum {
FIRSTNAME,LASTNAME,AGE;
}
Note: if the conditions are suitable for you, you can also use the appropriate conditions
I hope it can help you solve the problem
