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) {
// ?
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With