我有一组元素,它们之间有距离测量。我正在寻找一种方法来找到该集合中最接近的元素对。使用循环我将使用以下算法:
double minDistance = Double.MAX_VALUE;
AbstractMap.SimpleEntry<Element, Element> closestPair;
for (Element element1 : elements) {
for (Element element2 : elements) {
double currentDistance = element1.distance(element2);
if (!element1.equals(element2) && currentDistance < minDistance) {
minDistance = currentDistance;
closestPair = new AbstractMap.SimpleEntry(element1, element2);
}
}
}
是否有一种优雅的方式使用 Java 流来实现该算法?
最佳答案
也许是这样的:
Optional<SimpleEntry> closestPair = elements.stream()
.flatMap(elem -> elements.stream()
.filter(other -> !elem.equals(other))
.map(other -> new SimpleEntry(elem, other))
.min(Comparator.comparingDouble(e -> e.getKey().distance(e.getValue()));
但是您可能希望将这些内联 lambda 提取为单独的方法。
关于java - 使用 Java 流查找集合中最接近的对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65952678/