0

I have this hashmap of students which stores the id, name and last name. So I created this :

Map<Interger, HashMap<String,String>> students = new HashMap<>();

where the second hashmap stores the name and lastname. My goal is to look for a student in a swing application, I succeed in searching with id because it's the key of the first hashmap, but i'd like to use all of them like this:

enter image description here

So my question is : If I want to search by name or last name, how can i get the value of the first hashmap and put it in a new hashmap ?

3
  • 1
    You could maintain 3 hashmaps (id as key, name as key etc) but there's a good chance of last name / name collision, so I would iterate for name and last name. Also you really should use a Student object Commented Sep 30, 2015 at 17:15
  • Why do you make your own task more complex? Java is an OO language. Define classes and use them. Use a Map<Integer, Student> instead of storing the fields of a student in a HashMap. Commented Sep 30, 2015 at 17:17
  • I think I'll create a Student class and go from because it seems really much easier, thank you @JBNizet :D Commented Sep 30, 2015 at 17:37

3 Answers 3

1

You can iterate on the hashmap like this :

private int searchByName(String s) {
    for(Map.Entry<Integer, HashMap<String, String>> entry : students.entrySet()) {
        HashMap student = entry.getValue(); // Hashmap containing first and lastname
        if (student.containsKey(s)) // If name match
            return entry.getKey(); // Return the student ID
    }
    return 0; // Student not found
}

For the lastname just use containsValue(s) instead of containsKey(s)

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

Comments

0

You can use the Google Collections API Guava for that specifically a BiMap

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

With this you'will be able to search using first name and last name. This BiMap will be value to your first parent hashmap.

Comments

0

I am not sure if the data structure is the best for your use-case but answering to your question, you should try using values() method which would return you the collection of values of the Map

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#values()

Collection res =  studensts.values();

Iterator<HashMap<String, String>> i = res.iterator();
Map<String,String> resM = null;
while(i.hasNext()){
   resM = i.next();
}

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.