public class Student {
@Nonnull private String name;
private int age;
// конструктор
// геттеры и сеттеры
}
public class CheckFieldsOneByOne implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
int nameCompare = o1.getName().compareTo(o2.getName());
if(nameCompare != 0) {
return nameCompare;
}
return Integer.compare(o1.getAge(), o2.getAge());
}
}
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
public class ComparisonChainExample implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return ComparisonChain.start()
.compare(o1.getName(), o2.getName())
.compare(o1.getAge(), o2.getAge())
.result();
}
}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
public class CompareToBuilderExample implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return new CompareToBuilder()
.append(o1.getName(), o2.getName())
.append(o1.getAge(), o2.getAge())
.build();
}
}
public static Comparator<Student> createPersonLambdaComparator() {
return Comparator.comparing(Student::getName)
.thenComparing(Student::getAge);
}