如何在Java中按两个字段排序? [英] How to sort by two fields in Java?
问题描述
我有对象数组person (int age; String name;)
.
如何按名称和年龄的字母顺序对这个数组进行排序?
How can I sort this array alphabetically by name and then by age?
你会使用哪种算法?
推荐答案
您可以使用 Collections.sort
如下:
private static void order(List<Person> persons) {
Collections.sort(persons, new Comparator() {
public int compare(Object o1, Object o2) {
String x1 = ((Person) o1).getName();
String x2 = ((Person) o2).getName();
int sComp = x1.compareTo(x2);
if (sComp != 0) {
return sComp;
}
Integer x1 = ((Person) o1).getAge();
Integer x2 = ((Person) o2).getAge();
return x1.compareTo(x2);
}});
}
List
现在按姓名排序,然后按年龄排序.
List<Persons>
is now sorted by name, then by age.
String.compareTo
按字典顺序比较两个字符串" - 来自 文档.
String.compareTo
"Compares two strings lexicographically" - from the docs.
Collections.sort
是原生 Collections 库中的静态方法.它进行实际的排序,您只需要提供一个 Comparator 来定义应该如何比较列表中的两个元素:这是通过提供您自己的 compare
方法实现来实现的.
Collections.sort
is a static method in the native Collections library. It does the actual sorting, you just need to provide a Comparator which defines how two elements in your list should be compared: this is achieved by providing your own implementation of the compare
method.
这篇关于如何在Java中按两个字段排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!