Click here to Skip to main content
15,741,947 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all, in this method i am returning the person who is available and nearest to the given location, now i am trying to return the person who has a lower ID if more than one persons are nearest to the given location. (I can call a persons ID by the method person.getIdentity().) I am unsure how to do this however. This is my method so far.

What I have tried:

<pre>public Person findNearestAvailable(int location)
        Iterator<Person> it = persons.iterator();
        int nearestDistance = Integer.MAX_VALUE;
        Person nearestAssistant = null;
        while(it.hasNext()) // checks all persons
            Person person =;
            if(person.isAvailable()) //but only the availalble ones
                int distance = location - person.getLocation();
                if(distance < nearestDistance){
                    nearestDistance = distance;
                    nearestPerson = person;
        return nearestPerson;
Updated 20-Nov-22 11:06am

1 solution

Keep a reference to the last person at the same distance: each time you find a closer one, set it to that person. When you find another with the same distance, compare the ids and set it to the minimum one.
After the loop, you have the minimum distance, and lowest ID person.
Share this answer
OriginalGriff 21-Nov-22 8:43am    
Please allow me to quote yourself:
"I can call a persons ID by the method person.getIdentity()"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900