Using Java streams to find the closest pair in a set

Viewed 128

I have a set of elements that have a distance measure between them. I am looking for a way to find the closest pair of elements out of this set. Using loops I would use the following algorithm:

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);
        }
    }
}
            

Is there an elegant way to implement this algorithm using Java streams?

1 Answers

Something like this, perhaps:

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()));

But you may want to extract those inline lambdas as separate methods.

Related