【问题标题】:Sorting an ArrayList of objects using a custom sorting order使用自定义排序顺序对对象的 ArrayList 进行排序
【发布时间】:2010-12-21 07:24:52
【问题描述】:

我希望为我的地址簿应用程序实现排序功能。

我想对ArrayList<Contact> contactArray 进行排序。 Contact 是一个包含四个字段的类:姓名、家庭号码、手机号码和地址。我想对name进行排序。

如何编写自定义排序函数来做到这一点?

【问题讨论】:

    标签: java sorting collections arraylist


    【解决方案1】:

    你应该使用 Arrays.sort 函数。包含的类应该实现 Comparable。

    【讨论】:

    • 问题是 OP 使用的是 ArrayList,而不是数组。
    【解决方案2】:

    Collections.sort 是一个很好的排序实现。如果您没有为 Contact 实现可比较,则需要传入 Comparator implementation

    注意:

    排序算法是一种改进的归并排序(如果低位子列表中的最高元素小于高位子列表中的最低元素,则忽略合并)。该算法提供有保证的 n log(n) 性能。指定的列表必须是可修改的,但不必调整大小。这个实现将指定的列表转储到一个数组中,对数组进行排序,并遍历列表,从数组中的相应位置重置每个元素。这避免了由于尝试对链表进行排序而导致的 n2 log(n) 性能。

    归并排序可能比你能做的大多数搜索算法都要好。

    【讨论】:

      【解决方案3】:

      这是一个关于排序对象的教程:

      虽然我会举一些例子,但我还是建议阅读。


      有多种方法可以对ArrayList 进行排序。如果你想定义一个natural(默认)ordering,那么你需要让Contact实现Comparable。假设您想在name 上默认排序,然后执行(为简单起见省略了空值检查):

      public class Contact implements Comparable<Contact> {
      
          private String name;
          private String phone;
          private Address address;
      
          @Override
          public int compareTo(Contact other) {
              return name.compareTo(other.name);
          }
      
          // Add/generate getters/setters and other boilerplate.
      }
      

      这样你就可以做

      List<Contact> contacts = new ArrayList<Contact>();
      // Fill it.
      
      Collections.sort(contacts);
      

      如果你想定义一个外部可控排序(覆盖自然排序),那么你需要创建一个Comparator

      List<Contact> contacts = new ArrayList<Contact>();
      // Fill it.
      
      // Now sort by address instead of name (default).
      Collections.sort(contacts, new Comparator<Contact>() {
          public int compare(Contact one, Contact other) {
              return one.getAddress().compareTo(other.getAddress());
          }
      }); 
      

      您甚至可以在Contact 本身中定义Comparators,这样您就可以重复使用它们,而不是每次都重新创建它们:

      public class Contact {
      
          private String name;
          private String phone;
          private Address address;
      
          // ...
      
          public static Comparator<Contact> COMPARE_BY_PHONE = new Comparator<Contact>() {
              public int compare(Contact one, Contact other) {
                  return one.phone.compareTo(other.phone);
              }
          };
      
          public static Comparator<Contact> COMPARE_BY_ADDRESS = new Comparator<Contact>() {
              public int compare(Contact one, Contact other) {
                  return one.address.compareTo(other.address);
              }
          };
      
      }
      

      可以这样使用:

      List<Contact> contacts = new ArrayList<Contact>();
      // Fill it.
      
      // Sort by address.
      Collections.sort(contacts, Contact.COMPARE_BY_ADDRESS);
      
      // Sort later by phone.
      Collections.sort(contacts, Contact.COMPARE_BY_PHONE);
      

      为了达到最佳效果,您可以考虑使用通用 javabean 比较器

      public class BeanComparator implements Comparator<Object> {
      
          private String getter;
      
          public BeanComparator(String field) {
              this.getter = "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
          }
      
          public int compare(Object o1, Object o2) {
              try {
                  if (o1 != null && o2 != null) {
                      o1 = o1.getClass().getMethod(getter, new Class[0]).invoke(o1, new Object[0]);
                      o2 = o2.getClass().getMethod(getter, new Class[0]).invoke(o2, new Object[0]);
                  }
              } catch (Exception e) {
                  // If this exception occurs, then it is usually a fault of the developer.
                  throw new RuntimeException("Cannot compare " + o1 + " with " + o2 + " on " + getter, e);
              }
      
              return (o1 == null) ? -1 : ((o2 == null) ? 1 : ((Comparable<Object>) o1).compareTo(o2));
          }
      
      }
      

      你可以按如下方式使用:

      // Sort on "phone" field of the Contact bean.
      Collections.sort(contacts, new BeanComparator("phone"));
      

      (正如您在代码中看到的那样,可能已经覆盖了 null 字段以避免在排序期间出现 NPE)

      【讨论】:

      • 我会添加预定义多个比较器的可能性,然后按名称使用它们...
      • 其实我就是这么做的。比试图解释自己更容易。
      • @BalusC:没有问题。我不能相信这个想法,我从String.CASE_INSENSITIVE_ORDER 和朋友那里得到它,但我喜欢它。使生成的代码更易于阅读。
      • 那些 Comparator 定义可能也应该是 static 也可能是 final ......或者类似的东西......
      • 呵呵... BeanComparator 就像棒棒哒! :-)(我不记得空值的确切逻辑比较,但它是否需要在该返回行的开头有一个(o1 == null &amp;&amp; o2 == null) ? 0 :?)
      【解决方案4】:

      您需要让您的联系人类实现Comparable,然后实现compareTo(Contact) 方法。这样,Collections.sort 将能够为您对它们进行排序。根据我链接到的页面, compareTo '返回负整数、零或正整数,因为此对象小于、等于或大于指定对象。'

      例如,如果您想按名称(A 到 Z)排序,您的类将如下所示:

      public class Contact implements Comparable<Contact> {
      
          private String name;
      
          // all the other attributes and methods
      
          public compareTo(Contact other) {
              return this.name.compareTo(other.name);
          }
      }
      

      【讨论】:

      • 与我合作得很好,谢谢!我还使用 compareToIgnoreCase 来忽略大小写。
      【解决方案5】:

      This page 告诉你所有你需要知道的关于排序集合的知识,比如 ArrayList。

      基本上你需要

      • 让你的Contact类实现Comparable接口
        • 在其中创建一个方法public int compareTo(Contact anotherContact)
      • 完成此操作后,您只需致电Collections.sort(myContactList);
        • 其中myContactListArrayList&lt;Contact&gt;(或Contact 的任何其他集合)。

      还有另一种方法,涉及创建一个 Comparator 类,您也可以从链接页面中了解它。

      例子:

      public class Contact implements Comparable<Contact> {
      
          ....
      
          //return -1 for less than, 0 for equals, and 1 for more than
          public compareTo(Contact anotherContact) {
              int result = 0;
              result = getName().compareTo(anotherContact.getName());
              if (result != 0)
              {
                  return result;
              }
              result = getNunmber().compareTo(anotherContact.getNumber());
              if (result != 0)
              {
                  return result;
              }
              ...
          }
      }
      

      【讨论】:

        【解决方案6】:

        BalusC 和 bguiz 已经就如何使用 Java 内置的比较器给出了非常完整的答案。

        我只想补充一点,google-collections 有一个Ordering 类,它比标准比较器更“强大”。 这可能值得一试。您可以做一些很酷的事情,例如复合排序、反转排序、根据函数对对象的结果进行排序...

        Here 是一篇博文,其中提到了它的一些好处。

        【讨论】:

        • 请注意,google-collections 现在是 Guava(Google 的通用 Java 库)的一部分,因此如果您想使用 Ordering 类,您可能需要依赖 Guava(或 Guava 的集合模块)。
        【解决方案7】:

        通过使用lambdaj,您可以按如下方式对联系人集合进行排序(例如按他们的姓名)

        sort(contacts, on(Contact.class).getName());
        

        或通过他们的地址:

        sort(contacts, on(Contacts.class).getAddress());
        

        等等。更一般地说,它提供了一个 DSL 以多种方式访问​​和操作您的集合,例如根据某些条件过滤或分组您的联系人,聚合他们的一些属性值等。

        【讨论】:

          【解决方案8】:

          我是通过以下方式做到的。 number 和 name 是两个数组列表。我必须对 name 进行排序。如果 name arralist 顺序发生任何变化,那么 number arraylist 也会改变它的顺序。

          public void sortval(){
          
                  String tempname="",tempnum="";
          
                   if (name.size()>1) // check if the number of orders is larger than 1
                      {
                          for (int x=0; x<name.size(); x++) // bubble sort outer loop
                          {
                              for (int i=0; i < name.size()-x-1; i++) {
                                  if (name.get(i).compareTo(name.get(i+1)) > 0)
                                  {
          
                                      tempname = name.get(i);
          
                                      tempnum=number.get(i);
          
          
                                     name.set(i,name.get(i+1) );
                                     name.set(i+1, tempname);
          
                                      number.set(i,number.get(i+1) );
                                      number.set(i+1, tempnum);
          
          
                                  }
                              }
                          }
                      }
          
          
          
          }
          

          【讨论】:

          • 您将花费更长的时间来编写这个,获得不太理想的排序性能,编写更多的错误(希望更多的测试),并且代码将更难转移给其他人。所以这是不对的。它可能有效,但它并不能使它正确。
          【解决方案9】:

          除了已经发布的内容之外,您应该知道,从 Java 8 开始,我们可以缩短代码并将其编写为:

          Collection.sort(yourList, Comparator.comparing(YourClass::getFieldToSortOn));
          

          或者由于 List 现在有 sort 方法

          yourList.sort(Comparator.comparing(YourClass::getFieldToSortOn));
          

          说明:

          从 Java 8 开始,功能接口(只有一种抽象方法的接口 - 它们可以有更多默认或静态方法)可以使用以下方法轻松实现:

          由于Comparator&lt;T&gt;只有一个抽象方法int compare(T o1, T o2),它是函数式接口。

          所以而不是(来自@BalusCanswer 的示例)

          Collections.sort(contacts, new Comparator<Contact>() {
              public int compare(Contact one, Contact other) {
                  return one.getAddress().compareTo(other.getAddress());
              }
          }); 
          

          我们可以将这段代码简化为:

          Collections.sort(contacts, (Contact one, Contact other) -> {
               return one.getAddress().compareTo(other.getAddress());
          });
          

          我们可以通过跳过来简化这个(或任何)lambda

          • 参数类型(Java 将根据方法签名推断它们)
          • {return ... }

          所以不是

          (Contact one, Contact other) -> {
               return one.getAddress().compareTo(other.getAddress();
          }
          

          我们可以写

          (one, other) -> one.getAddress().compareTo(other.getAddress())
          

          现在Comparator 也有像comparing(FunctionToComparableValue)comparing(FunctionToValue, ValueComparator) 这样的静态方法,我们可以使用它们轻松地创建比较器来比较对象中的一些特定值。

          换句话说,我们可以将上面的代码重写为

          Collections.sort(contacts, Comparator.comparing(Contact::getAddress)); 
          //assuming that Address implements Comparable (provides default order).
          

          【讨论】:

            【解决方案10】:

            使用这个方法:

            private ArrayList<myClass> sortList(ArrayList<myClass> list) {
                if (list != null && list.size() > 1) {
                    Collections.sort(list, new Comparator<myClass>() {
                        public int compare(myClass o1, myClass o2) {
                            if (o1.getsortnumber() == o2.getsortnumber()) return 0;
                            return o1.getsortnumber() < o2.getsortnumber() ? 1 : -1;
                        }
                    });
                }
                return list;
            }
            

            `

            并使用:mySortedlist = sortList(myList); 无需在您的类中实现比较器。 如果你想逆序交换1-1

            【讨论】:

              【解决方案11】:

              好的,我知道很久以前就有人回答了……但是,这里有一些新信息:

              假设有问题的 Contact 类已经通过实现 Comparable 定义了自然排序,但您想覆盖该排序,比如按名称。这是现代的做法:

              List<Contact> contacts = ...;
              
              contacts.sort(Comparator.comparing(Contact::getName).reversed().thenComparing(Comparator.naturalOrder());
              

              这样,它将首先按名称排序(以相反的顺序),然​​后对于名称冲突,它将回退到 Contact 类本身实现的“自然”排序。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-10-28
                • 1970-01-01
                相关资源
                最近更新 更多