Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap<String, Object> - How to return an Object having only its argument?

Tags:

java

hashmap

key

Given the following details I need to write a method which returns an Object Person:

public class Person {

    private String firstName;
    private String lastName;
    private int deskNo;
    private String departmentName;
    ...
}
// this class also contains get methods for each argument

Objects Person are stored in a HashMap, where Key is same as lastName for each Object. Value is obviously Person Object.

private final Map<String, Person> employeeHM = new HashMap<>();
...
employeeHM.put("Doe", new Person("Jon", "Doe", 14, "Sales");

I approached this problem with several solutions but failed in each instance. Is there a way do directly compare the firstName with lastName and return matching Object? One of my ideas was to use a Set or a Colleciton, but I am fairly sure this is overcomplicating things.

@Override
public Person findPersonByFirstName(String firstName) {
   // ?
}
like image 768
JDelorean Avatar asked Jan 07 '23 02:01

JDelorean


1 Answers

just iterate through your map and find the person which the right first name:

private Person getPersonByFirstName(String firstName) {
    for (Person p : employeeHM.values()) {
        if (p.getFirstName().equals(firstName))
           return p;
    }
    return null;
}

Please note that this will give you the first person found that has the correct firstname. If multiple persons do have the same firstname it might be random which one you get.

like image 200
ParkerHalo Avatar answered Jan 21 '23 07:01

ParkerHalo