4

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) {
   // ?
}
5
  • 5
    Aside: If you are using lastName as the key, you won't be able to have both John and Jane Doe in your map. Commented Nov 30, 2015 at 13:38
  • In my case it doesn't matter if you search by first or last name. Just saying :/ Commented Nov 30, 2015 at 13:39
  • @MarounMaroun Your name is obviously a bug. Fix it :D Commented Nov 30, 2015 at 13:41
  • 3
    You might consider using a database. Commented Nov 30, 2015 at 13:43
  • Btw. Thank you all for your swift responses! It's great to know there's a whole community ready to jump in and help a newbie sort things out. You are awesome! Commented Nov 30, 2015 at 14:34

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! My impression with employeeHM.values() was that I needed to input something in the brackets. This solves the problem. Much appreciated!
You're welcome. But if you're not using the last name (the key of the map) at all you might want to rethink your concept... If we're just not seeing the part where you use the last name then everything is fine ;)
No, you're not seeing that part. I got that figured out already ;)
2

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.

Comments

2

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.

Comments

1

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 i.e. 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.

2 Comments

Thanks. Yes, a DB sounds like a good solution to most ideas where it is difficult to estimate if the number of "rows" will be finite or not.
I didn't mean a DB because of persistence or size, I mean a DB because of having a query language associated which is what you need if the problem scales further.
1

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.