Home  >  Article  >  Java  >  How to Sort Lists of Objects with Multiple Fields in Java?

How to Sort Lists of Objects with Multiple Fields in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-04 08:20:30915browse

How to Sort Lists of Objects with Multiple Fields in Java?

Sorting Lists of Objects with Multiple Fields:

In the initial sorting code provided, the concatenation of the fields in the comparison makes it challenging to separate the fields for sorting. To rectify this, consider adding spaces between the fields. Alternatively, you can explore the following alternatives:

Using Java 8 Lambdas:

Collections.sort(reportList, Comparator.comparing(Report::getReportKey)

    .thenComparing(Report::getStudentNumber)
    .thenComparing(Report::getSchool));

Reflective Method: BeanComparator:

ComparatorChain chain = new ComparatorChain(Arrays.asList(
new BeanComparator("size"),
new BeanComparator("nrOfToppings"),
new BeanComparator("name")));

Collections.sort(pizzas, chain);

Guava's ComparisonChain:

Collections.sort(pizzas, new Comparator() {

@Override  
public int compare(Pizza p1, Pizza p2) {  
    return ComparisonChain.start().compare(p1.size, p2.size).compare(p1.nrOfToppings, p2.nrOfToppings).compare(p1.name, p2.name).result();  
}  

});

Apache Commons CompareToBuilder:

Collections.sort(pizzas, new Comparator() {

@Override  
public int compare(Pizza p1, Pizza p2) {  
    return new CompareToBuilder().append(p1.size, p2.size).append(p1.nrOfToppings, p2.nrOfToppings).append(p1.name, p2.name).toComparison();  
}  

});

The above is the detailed content of How to Sort Lists of Objects with Multiple Fields in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn