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:
Collections.sort(reportList, Comparator.comparing(Report::getReportKey)
.thenComparing(Report::getStudentNumber) .thenComparing(Report::getSchool));
ComparatorChain chain = new ComparatorChain(Arrays.asList(
new BeanComparator("size"),
new BeanComparator("nrOfToppings"),
new BeanComparator("name")));
Collections.sort(pizzas, chain);
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(); }
});
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!