【问题标题】:Sorting Array in Numerical Order by Object's Property [duplicate]按对象的属性按数字顺序对数组进行排序[重复]
【发布时间】:2015-12-04 03:06:23
【问题描述】:

我正在努力按对象属性的顺序对数组进行排序。我知道如何按顺序对数字进行排序,但我不知道如何对对象进行排序。例如,假设对象 A 的位置属性为 1,对象 B 的位置属性为 2。这些对象位于数组中。我怎样才能根据这个属性对它们进行排序?

谢谢

【问题讨论】:

    标签: java arrays sorting


    【解决方案1】:

    你有类似的东西:

    public class ExampleObject {
        public int position;
    }
    

    然后,只需使用Comparator

    public static void main(String args[]) {
        //example numbers
        final Random r = new Random();
        final List<ExampleObject> arrList = new ArrayList<>(100);
        for (int i = 0; i < 100; i++) {
            ExampleObject obj = new ExampleObject();
            obj.position = r.nextInt(1000);
            arrList.add(obj);
        }
    
        //comparator (as a lambda)
        Collections.sort(arrList, (a, b) -> {
            return a.position - b.position;
        });
    
        //output result
        for (ExampleObject obj : arrList) {
            System.out.println(obj.position);
        }
    }
    

    另外,如果您必须对数组而不是List 进行排序,您也可以像这样使用Arrays.sort()Comparator

    【讨论】:

      【解决方案2】:

      您可以通过在您的类中实现Comparable 接口来进行比较,如下所示。

      public class Applcation {
          public static void main(String[] args) {
              A ary[] = {new A("D", 1),new A("C", 7),new A("K", 4),new A("L", 8),new A("S", 3)};
              Arrays.sort(ary);
              for (A a : ary) {
                  System.out.println(a.id+" - "+a.name);
              }
          }
      
      }
      class A implements Comparable<A>{
      
          String name;
          int id;
      
          public A(String name, int id) {
              this.name = name;
              this.id = id;
          }
      
          @Override
          public int compareTo(A a) {
              return this.id-a.id;
          }
      
      
      }
      

      或者作为替代方案,您可以使用 java 8 流对数组进行排序,而无需实现 Comparable

      Arrays.stream(ary).sorted((a1,a2)->Integer.compare(a1.id, a2.id)).forEach(e->System.out.println(e.id+" - "+e.name));
      

      输出:

      1 - D
      3 - S
      4 - K
      7 - C
      8 - L         
      

      【讨论】:

        猜你喜欢
        • 2018-10-11
        • 2013-11-02
        • 2016-11-25
        • 1970-01-01
        • 1970-01-01
        • 2019-05-29
        • 2012-10-06
        • 2014-09-17
        相关资源
        最近更新 更多