如何在Java中按两个字段排序? [英] How to sort by two fields in Java?

查看:2507
本文介绍了如何在Java中按两个字段排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象数组 person(int age; String name;)

我如何排序这个数组按名称按字母顺序排列,然后按年龄排列?

How can I sort this array alphabetically by name and then by age?

你会使用哪种算法?

推荐答案

您可以使用 Collections.sort ,如下所示:

You can use Collections.sort as follows:

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<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆