繁体   English   中英

如何使用Java 8中的比较器按参数对流进行排序?

[英]How to sort a stream by parameter using a comparator in Java 8?

如何使用Java 8中的比较器和参数对集合进行排序?

这是一段代码:

    List<Point> sortedNeurons = neurons.parallelStream()
        .sorted((n1, n2) -> Double.compare(
            n1.getEuclideanDistanceFrom(inputVector),
            n2.getEuclideanDistanceFrom(inputVector)))
        .collect(Collectors.toList());

您将获得一个参数inputVector,该参数可以传递给返回原始double值的函数。 如果应用于集合的元素,则返回一些数字。 我希望通过此值对集合进行排序。 类似于:通过getEuclideanDistanceFrom(inputVector,id)从神经元中选择id;

这里有三个问题:

  1. nx.getEuclideanDistanceFrom(inputVector)重复两次。
  2. 我想在使用order by子句时使用double类型的自然排序,而不是像在SQL查询中那样声明它。
  3. 也许n1,n2 - > n1,n2可以用双冒号::符号代替。

PS我有一种强烈的感觉,它可以使用像双功能或双音素这样的东西来修复......但是无法弄清楚...

也许你可以用Comparator#comparingDouble来做到这一点:

List<Point> sortedNeurons = neurons.parallelStream()
    .sorted(Comparator.comparingDouble(p -> p.getEuclideanDistanceFrom(inputVector)))
    .collect(Collectors.toList());

这看起来不错。 我做得更好:

List<Point> sortedNeurons = neurons.parallelStream()
    .sorted(Comparator.comparingDouble(inputVector::getEuclideanDistanceFrom))
    .collect(Collectors.toList());

然后我意识到,你可以做得更短:

List<Point> sortedNeurons =
neurons.sort(Comparator.comparingDouble(inputVector::getEuclideanDistanceFrom));

显然溪流不适合分类......

我还找到了一种方法来提取可以重用的比较器:

public interface Functional<T> {
    public int compareByEuclideanDistance(T o1, T o2);
}

public class Point implements Functional<Point> {
    @Override
    public int compareByEuclideanDistance(Point o1, Point o2) {
        return Double.compare(this.getEuclideanDistanceFrom(o1),
            this.getEuclideanDistanceFrom(o2));
    }
}

现在您可以拨打任何电话,例如:

neurons.parallelStream()
    .sorted(input::compareByEuclideanDistance)
    .collect(Collectors.toList());

要么

neurons.parallelStream().min(input::compareByEuclideanDistance).get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM