简体   繁体   中英

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

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.

I don't write code for you. But below are my thoughts.

Just get all the values of Map ( map.values() ). And iterate over them. Check if the first name is matched and return it. See that you may end up with multiple persons, who have same first name, hence the return type may required to change.

And another suggestion would be, using first or last name as Map's key is a worse idea almost. If I were you, I will use his Id or DeskNo as a key which is unique.

As others already suggested, this can be achieved if you iterate on the values instead of the keys.

But is that really what you want to do? If yes, why not having the first name as a key instead? The idea of Map is that for each unique key you have one or more values, getting from a Map has O(1) complexity. Iterating of value to get a key is a little bit weird and it has O(n) complexity.

In this case, I highly advise you to reconsider your data structure and try to have something more appropriate for your usage.

First of all you should reconsider the use of HashMap in this circumstance since apparently your key is not always the same. What you are trying to achieve is pretty much data-set mechanics, you could consider the use of a DB and a proper query language.

There is absolutely no reason to use a hashMap unless your entity (Person) actually has some sort of key ie one field that prominently identifies the entity.

As a quick fix, if you are using Java8 you can easily achieve the desired result with lambda expressions:

private final Collection<Person> employeeHM = new HashSet<>();

employeeHM.add(new Person("Jon", "Doe", 14, "Sales"));

and parse the collection as such:

Person employeeDoe = employeeHM.stream().filter(person -> person.getLastName().equals("Doe")).findFirst().orElse(null);

Person employeeJon = employeeHM.stream().filter(person -> person.getFirstName().equals("Jon")).findFirst().orElse(null);

Notice this will return the first element that matches the filter lambda and null if none are found.

Also the fact that the parsing is done inline removes the need for specific find methods like the one you have. Just call the lambda expression wherever you want and all magic is done on your behalf by the Java framework.

I think what you look for, is to find a person with given first- and last-names, while storing in the HashMap given.

You could do a List as Value (and traverse it) or to do it hardcore with a HashMap of HashMaps. Or you could just use a Key-Value Object for Name as Key.

private final Map<String, Map<String, Person>> employeeHM = new HashMap<>();

Map<String, Person> value = employeeHM.get("Doe");
if (value == null) {
  value = new HashMap<String, Person>();
  employeeHM.put("Doe", value);
}
value.put("Jon", new Person("Jon", "Doe", 14, "Sales");

GET is done by:

Map<String, Person> does = employeeHM.get("Doe")
Person jonDoe = does.get("Jon");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM