HashMap在Java中的Hashmap中的值(Value of HashMap inside a Hashmap in Java)

编程入门 行业动态 更新时间:2024-10-27 06:23:35
HashMap在Java中的Hashmap中的值(Value of HashMap inside a Hashmap in Java)

我有这个学生的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)

更多推荐

本文发布于:2023-07-15 15:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1115293.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:HashMap   Java   Hashmap

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!