简体   繁体   English

Java中的Hashmap内HashMap的值

[英]Value of HashMap inside a Hashmap in Java

I have this hashmap of students which stores the id, name and last name. 我有这个学生的哈希表,其中存储了ID,名称和姓氏。 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: 我的目标是在swing应用程序中寻找学生,我成功搜索了id,因为它是第一个哈希图的键,但是我想像这样使用所有这些对象:

在此处输入图片说明

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 ? 所以我的问题是:如果要按名称或姓氏搜索,如何获取第一个哈希图的值并将其放在新的哈希图中?

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) 对于姓氏,只需使用containsValue(s)而不是containsKey(s)

You can use the Google Collections API Guava for that specifically a BiMap 您可以使用Google Collections API Guava专门用于BiMap

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. bimap(或“双向地图”)是一种保留其值以及其键的唯一性的地图。 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. 此约束使bimap可以支持“反向视图”,这是另一个bimap,它包含与此bimap相同的条目,但具有相反的键和值。

With this you'will be able to search using first name and last name. 使用此功能,您将可以使用名字和姓氏进行搜索。 This BiMap will be value to your first parent hashmap. 此BiMap将成为您的第一个父哈希图的值。

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 我不确定数据结构是否适合您的用例,但要回答您的问题,您应该尝试使用values()方法,该方法将返回Map的值集合

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#values() 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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