【问题标题】:Java sort a list of pairs using both indexes [duplicate]Java使用两个索引对列表进行排序[重复]
【发布时间】:2021-08-21 07:01:22
【问题描述】:

我想根据两个索引对List<Pair<Long, Long>> list = new ArrayList<Pair<Long, Long>>(); 进行排序,首先根据第一个索引,如果第一个索引相等,则使用 Java 8 lambda 函数根据第二个索引。

我可以很容易地只按第一个索引排序: Collections.sort(list,(o1, o2) -> o1.first < o2.first ? -1:0);

如果我想根据两个索引进行排序 Collections.sort(list,(o1, o2) -> o1.first < o2.first ? -1 : o1.first == o2.first ? (o1.second < o2.second ? -1 : 0) : 0); 但我认为这不是正确的做法。有人可以提供更好的语法吗?

对定义:

    class Pair<Type1, Type2> {
        Type1 first;
        Type2 second;

        Pair(Type1 f, Type2 s) {
            this.first = f;
            this.second = s;
        }

        public String toString() {
            return "(" + this.first + ", " + this.second + ")";
        }
    }

【问题讨论】:

  • 当您看到比较器有时返回负数但从不返回正数时,您可以判断它已损坏。这显然违反了对称性要求。

标签: java java-8


【解决方案1】:

Collections.sort 与比较器构造函数一起使用,如下所示:

Collections.sort(list, 
    Comparator.comparing((Pair<Long, Long> p) -> p.first)
        .thenComparing(p -> p.second));

更新

或者,正如下面评论中所建议的,您可以使用List.sort,它比上面使用的实用方法更简洁。

list.sort(Comparator.comparing((Pair<Long, Long> p) -> p.first)
    .thenComparing(p -> p.second));

【讨论】:

  • 也可以直接使用list.sort(…)
  • 当然,不错。当图书馆作者提供不同的方法来做同样的事情时,有时会让人感到困惑。然而,建议的方法更简洁,值得一提作为更新。特定于List 的实现是否会对实用方法Collections.sort 使用一些特定的优化?
  • 在常用的ArrayList的情况下,sort方法已被覆盖以跳过default方法的复制步骤,但是,由于Java 8, update 20Collections.sort(…)方法只是委托给list.sort(…),因此您可以自动获得专门实现的优势。所以,两者都会做同样的事情,但list.sort(…) 更简单。
  • 是的,我猜 list.sort 更具可读性。感谢您的详细解释。
猜你喜欢
  • 2018-01-30
  • 1970-01-01
  • 2012-09-07
  • 2021-04-15
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
  • 2023-03-17
相关资源
最近更新 更多