HashMap在多个键中搜索特定值 [英] HashMap Searching For A Specific Value in Multiple Keys

查看:144
本文介绍了HashMap在多个键中搜索特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查我的HashMap中是否存在一个密钥,如果存在,我还想检查其他密钥的值是否与我检查的原始密钥名称相同。

例如我有这个。

  System.out。 println(你想搜索什么课程?); 
String searchcourse = input.nextLine();
布尔coursefound = false;

if(hashmap.containsKey(searchcourse)== true){
coursefound = true;





检查密钥是否存在于我的散列表中,但现在我需要检查每一个键的值的具体值,在这种情况下,字符串searchcourse。

通常我会使用一个基本的循环遍历这样的事情,但它不适用于HashMaps。我的值也存储在String ArrayList中,如果有帮助的话。

解决方案

你会想看看HashMap 。这个循环应该为你的 searchcourse 检查ArrayList的内容,并打印出包含该值的键。



<$ p (Map.Entry< String,ArrayList>条目:hashmap.entrySet()){
if(entries.getValue()。contains(searchcourse)){
System.out.println(entries.getKey()+contains+ searchcourse);


以下是相关的javadoc:



地图.Entry



HashMap entrySet 方法
$ b

<一个href =http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#contains%28java.lang.Object%29 =nofollow> ArrayList 包含方法


I'm checking to see if a key in my HashMap exists, if it does, I also want to check to see if any other keys have a value with the same name as that of the original key I checked for or not.

For example I have this.

System.out.println("What course do you want to search?");
    String searchcourse = input.nextLine();
boolean coursefound = false;

if(hashmap.containsKey(searchcourse) == true){
    coursefound = true;
        }

This checks to see if the key exists in my hashmap, but now I need to check every single key's values for a specific value, in this case the string searchcourse.

Usually I would use a basic for loop to iterate through something like this, but it doesn't work with HashMaps. My values are also stored in a String ArrayList, if that helps.

解决方案

You will want to look at each entry in the HashMap. This loop should check the contents of the ArrayList for your searchcourse and print out the key that contained the value.

for (Map.Entry<String,ArrayList> entries : hashmap.entrySet()) {
    if (entries.getValue().contains(searchcourse)) {
        System.out.println(entries.getKey() + " contains " + searchcourse);
    }
}

Here are the relevant javadocs:

Map.Entry

HashMap entrySet method

ArrayList contains method

这篇关于HashMap在多个键中搜索特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆