Find the closest unvisited visible home I'm writing a 2d top down game where I perform a lot of "closest" searches between one point and all the rest of the points.

In this example, "me" wants to search for the closest visible house (Home) that I haven't visited yet, and if it is not found, return null.

protected Home getClosestUnvisitedVisibleHome(Person me, final int VISIBLE_ZONE) {
    List&lt;Home&gt; visitedHomes = me.getVisitedHomes();
    Map&lt;Home, Integer&gt; homeDistances = new HashMap&lt;&gt;();
    List&lt;Home&gt; allHomes = getHomes();
    allHomes.stream().parallel().forEach(home -&gt; homeDistances.put(home, range(me, home)));
    List&lt;Home&gt; unvisitedVisibleHomes = allHomes.stream().parallel().filter(
            home -&gt; !visitedHomes.contains(home) &amp;&amp; homeDistances.get(home) &lt;= VISIBLE_ZONE
    ).collect(Collectors.toList());
    unvisitedVisibleHomes.sort((home1, home2) -&gt; homeDistances.get(home1).compareTo(homeDistances.get(home2)));
    try {
        return unvisitedVisibleHomes.get(0);
    } catch (IndexOutOfBoundsException e) {
        return null;
    }
}

protected int range(VisibleEntity visibleEntity, VisibleEntity me) {
    return (int)Math.sqrt(Math.pow((visibleEntity.xy[0] - me.xy[0]), 2) + Math.pow((visibleEntity.xy[1] - me.xy[1]), 2));
}


I'm looking for suggestions on how to optimize this particular function and or any suggestions of its content.
I don't see why you use a HashMap (or any Map) at all.

What I'd do is:


Get all the homes
Filter all the homes to only get those which are unvisited
Get the home that is closest


The home that you get will either be visible, or it won't be visible. If it is not visible, there won't be any other visible homes either.

Combining this with @Vogel's suggestion of using Set the code would go something like this:

Set&lt;Home&gt; visitedHomes = me.getVisitedHomes();
Set&lt;Home&gt; allHomes = getHomes();
Optional&lt;Home&gt; result = allHomes.stream().parallel()
    .filter(home -&gt; !visitedHomes.contains(home))
    .min(Comparator.comparingInt(home -&gt; range(me, home)))
    .map(result -&gt; range(me, result) &lt;= VISIBLE_ZONE ? result : null);


And then you can choose between either returning the optional:

return result;


or returning null if there is no match:

return result.orElse(null);