Home > Java > javaTutorial > body text

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

Barbara Streisand
Release: 2024-11-04 08:20:30
Original
914 people have browsed it

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));
Copy after login

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();  
}  
Copy after login

});

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();  
}  
Copy after login

});

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template