根据方法的结果对 ArrayList 进行排序

Sorting an ArrayList based on the result of a method

我在 ArrayList 中有这些对象:

public class Foo implements Comparable<Foo> {
    ...
    private ArrayList<Double> coordinates;
    ...
}

而且我的主要 class 中有一个方法输出 2 个点之间的距离,称为 :

p2pDistance(Foo x, Foo b)

我想做的是根据调用给定的值对列表进行排序 p2pDistance(root,elem) root 是 Foo 的一个实例,不在原始列表中。

我的尝试是执行以下操作:

data.sort((o1, o2) -> (int) p2pDistance(root, o1));

(或等效的非 lambda 表达式):

data.sort(new Comparator<Foo>() {
    @Override
    public int compare(Foo o1, Foo o2) {
        return (int) Main.this.p2pDistance(root, o1);
    }
});

但是,这并没有奏效。 我的猜测是制作一个循环遍历 List 并保留最小结果的方法,但我想知道为什么我的方法不起作用,以及是否还有一个优雅的解决方案。 (无需遍历列表并找到最低结果).

Comparable 想要三个结果之一:

  • 一个值-o1 < o2
  • 一个 值 - o1 = o2
  • 一个值-o1 > o2

据推测,您的 distance 函数总是返回正值。所以你可能只是颠倒了点的顺序。

看起来你想要的是比较两个点到根的距离,而不仅仅是 o1。所以,像

return p2pDistance(root, o1) - p2pDistance(root, o2);

这将根据对象到根点的距离(无论是什么)对列表中的 WadingPool 个对象进行排序。

在您的代码 data.sort((o1, o2) -> (int) p2pDistance(root, o1)); 中,您实际上并没有比较 o1o2。比较的结果是 return 距离,而比较器应该 return

a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

尝试使用data.sort(Comparator.comparingDouble(x -> p2pDistance(x, root)));

.comparingDouble 的参数是 ToDoubleFunction<? super T> keyExtractor,它允许您将任何对象映射到双精度值。