如何使用Java 8中的比较器和参数对集合进行排序?
这里有一段代码:
List<Point> sortedNeurons = neurons.parallelStream()
.sorted((n1, n2) -> Double.compare(
n1.getEuclideanDistanceFrom(inputVector),
n2.getEuclideanDistanceFrom(inputVector)))
.collect(Collectors.toList());
你被赋予一个参数inputVector,可以将其传递给返回原始double值的函数。如果应用于集合的元素,则返回某个数字。 我希望按照这个值对集合进行排序。 类似于:select id from neurons order by getEuclideanDistanceFrom(inputVector,id);
以下是三个问题:
1. nx.getEuclideanDistanceFrom(inputVector) 会重复两次。 2. 我想使用double类型的自然排序,不需要声明它,就像在SQL查询中使用order by子句一样。 3. 可以用双冒号::符号替换n1,n2 -> n1,n2。
附言:我强烈感觉可以使用类似于bifunction或biconsumer的东西来解决,但是无法弄清楚...
neurons.sort(Comparator.comparingDouble(inputVector::getEuclideanDistanceFrom));
- Lukasz Ochmanski