如何验证HashMap中是否存在值

Lui*_*eri 14 java android iterator arraylist hashmap

我有以下HashMap,其中keya是a String,value并由以下内容表示ArrayList:

 HashMap<String, ArrayList<String>> productsMap = AsyncUpload.getFoodMap();
Run Code Online (Sandbox Code Playgroud)

我还在ArrayList<String> foods我的应用程序中实现了另一个.

我的问题是,找出我的第二个HashMap包含特定内容的最佳方法是什么?StringArrayList

我试过没有成功:

Iterator<String> keySetIterator = productsMap.keySet().iterator();
Iterator<ArrayList<String>> valueSetIterator = productsMap.values().iterator();

    while(keySetIterator.hasNext() && valueSetIterator.hasNext()){
        String key = keySetIterator.next();
        if(mArrayList.contains(key)){
            System.out.println("Yes! its a " + key);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Men*_*ena 17

为什么不:

// fast-enumerating map's values
for (ArrayList<String> value: productsMap.values()) {
    // using ArrayList#contains
    System.out.println(value.contains("myString"));
}
Run Code Online (Sandbox Code Playgroud)

如果你必须迭代整体ArrayList<String>,而不是只查找一个特定的值:

// fast-enumerating food's values ("food" is an ArrayList<String>)
for (String item: foods) {
    // fast-enumerating map's values
    for (ArrayList<String> value: productsMap.values()) {
        // using ArrayList#contains
        System.out.println(value.contains(item));
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

过去我用一些Java 8成语更新了这个.

Java 8流API允许以更具声明性(并且可以说是优雅)的方式处理这些类型的迭代.

例如,这是一种(稍微过于冗长)实现相同的方式:

// iterate foods 
foods
    .stream()
    // matches any occurrence of...
    .anyMatch(
        // ... any list matching any occurrence of...
        (s) -> productsMap.values().stream().anyMatch(
            // ... the list containing the iterated item from foods
            (l) -> l.contains(s)
        )
    )
Run Code Online (Sandbox Code Playgroud)

...这里有一种更简单的方法来实现相同的,最初迭代productsMap值而不是内容foods:

// iterate productsMap values
productsMap
    .values()
    .stream()
    // flattening to all list elements
    .flatMap(List::stream)
    // matching any occurrence of...
    .anyMatch(
        // ... an element contained in foods
        (s) -> foods.contains(s)
    )
Run Code Online (Sandbox Code Playgroud)


Bla*_*rai 9

您需要使用该containsKey()方法.要做到这一点,你只需要获得你想要密钥的hashMap,然后使用containsKey方法,boolean如果有的话,它将返回一个值.这将搜索整个hashMap,而不必迭代每个项目.如果您有密钥,则只需检索该值即可.

它可能看起来像:

if(productsMap.values().containsKey("myKey"))
{
    // do something if hashMap has key
}
Run Code Online (Sandbox Code Playgroud)

这是Android的链接

来自Android文档:

public boolean containsKey(Object key)在API级别1中添加

返回此映射是否包含指定的键.参数键是要搜索的键.返回

true if this map contains the specified key, false otherwise.
Run Code Online (Sandbox Code Playgroud)

  • 为什么它命名为containsKey而不是containsValue?如果目的是知道它是否包含值. (2认同)