我有这个学生的hashmap,它存储了id,name和last name。 所以我创造了这个:
Map<Interger, HashMap<String,String>> students = new HashMap<>();其中第二个hashmap存储名称和姓氏。 我的目标是在swing应用程序中寻找一个学生,我成功地使用id进行搜索,因为它是第一个hashmap的关键,但是我想像这样使用所有这些:
所以我的问题是:如果我想按名称或姓氏搜索,我如何获得第一个hashmap的值并将其放入新的hashmap?
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:
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 ?
最满意答案
您可以像这样迭代hashmap:
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 }对于姓氏,只需使用containsValue(s)而不是containsKey(s)
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)
更多推荐
发布评论