我有一对配对列表,需要找到距离最小的所有配对。
class Pair {
...
distance
...
}
List<Pair> pairs = findAllDistances() // list that holds all pairs with distances
double minDistance = pairs.distance.min() // finds minimal distance, for example 1.0
// pairs list contains 15 elements with distance = 1.0
List<Pair> minDistancePairs = pairs.collect { it.distance = minDistance }
为什么我在计算后得到minDistancePairs = null
?
答案 0 :(得分:3)
你需要findAll,而不是收集
List<Pair> minDistancePairs = pairs.distance.min().with { min ->
pairs.findAll { it.distance == min }
}
答案 1 :(得分:2)
简单&#39; =&#39;是分配,双重&= 39; ==&#39;比较。假设您要收集距离等于&#39; minDistance&#39;的所有对,您应该这样做:
List<Pair> minDistancePairs = pairs.collect { it.distance == minDistance }