[英]Java Stream Sort - Comparator with 2 or more Criteria for Objects
[英]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;
這里有三個問題:
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.