简体   繁体   中英

How to return a key content from a HashMap in java?

Working on a small project which stores some students' records in a HashMap as database.

private HashMap<String, Student> studentDb = new HashMap<String, Student>();

My application has a UI which lets the users to choose any string as key record. It can be numbers or letters.Creating each record, creates an objects from another class which keeps information in its fields, but it is not suppose to store the key.

After storing all the data they can request to see all the data has been stored so far. The toSting method from the class which I instantiate my object from, generates the message to be displayed.

At the time of displaying, I need to display the key they chose with the rest of stored data and they may not ask for all of them. The question is, how can I get access to a given record's key? Let's say if I don't want to use key that user should enter at the time of their request. Is there any way to drive it from the HashMap collection?

I hope I could explain my question. Thank you.


Edit:

在此处输入图片说明

This is the output for a request, but the thing is I read the student's Id from the textfield they insert the request which is kind of cheating. I wondered if I can drive it from the collection itself.

Could use something like this:

Working version:

import java.util.HashMap;

public class test{

    public static void main(String[] args){

        HashMap<String, String> studentDb = new HashMap<String, String>();

        studentDb.put("1","A");
        studentDb.put("2","B");
        studentDb.put("3","C");

        for(String key : studentDb.keySet()){
            System.out.println(studentDb.get(key));
        }

    }
}

What you could do for your situation:

...

for(String key : studentDb.keySet()){
    if(studentDb.get(key)==/* STUDENT OBJECT */){
        // Display / do something with the key.
    }
}

...

What do you mean "to drive it from the HashMap collection"? Your hashmap stores data by key (in this case a String). In order to access a specific value, you need to know its key. If I understand correctly, what you want would be like doing something like :

map.get("myKey").getKey();

Which doesn't make sense. What you can do is iterate over all the keys in your map, with the keySet() method. But I'm not sure that's what you were looking for.

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