15

我有以下内容HashMap,其中keyaString和avalue由 a 表示ArrayList

 HashMap<String, ArrayList<String>> productsMap = AsyncUpload.getFoodMap();

我的应用程序中还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);
        }
    }
4

7 回答 7

18

为什么不:

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

如果你必须遍历整个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));
    }
}

编辑

过去我用一些 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)
        )
    )

...这是实现相同目的的更简单方法,最初迭代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)
    )
于 2013-08-22T19:25:01.310 回答
9

您需要使用该containsKey()方法。为此,您只需获取要从中取出键的 hashMap,然后使用该方法,如果这样做containsKey,它将返回一个值。boolean这将搜索整个 hashMap 而不必遍历每个项目。如果您确实有密钥,那么您可以简单地检索该值。

它可能看起来像:

if(productsMap.values().containsKey("myKey"))
{
    // do something if hashMap has key
}

这是安卓的链接

来自 Android 文档:

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

返回此映射是否包含指定的键。参数 key 要搜索的键。退货

true if this map contains the specified key, false otherwise.
于 2013-08-22T19:26:58.570 回答
3

尝试这个 :

public boolean anyKeyInMap(Map<String, ArrayList<String>> productsMap, List<String> keys) {
    Set<String> keySet = new HashSet<>(keys);

    for (ArrayList<String> strings : productsMap.values()) {
        for (String string : strings) {
            if (keySet.contains(string)) {
                return true;
            }
        }
    }

    return false;
}
于 2013-08-22T19:33:59.233 回答
3
hashMap.containsValue("your value");

将检查 HashMap 是否包含该值

于 2017-01-07T22:29:24.510 回答
1

这是测试这两种情况的示例方法。在地图的键中搜索项目,并在每个地图条目的列表中搜索项目:

private static void testMapSearch(){

    final ArrayList<String> fruitsList = new ArrayList<String>();        
    fruitsList.addAll(Arrays.asList("Apple", "Banana", "Grapes"));

    final ArrayList<String> veggiesList = new ArrayList<String>();        
    veggiesList.addAll(Arrays.asList("Potato", "Squash", "Beans"));

    final Map<String, ArrayList<String>> productsMap = new HashMap<String, ArrayList<String>>();

    productsMap.put("fruits", fruitsList);
    productsMap.put("veggies", veggiesList);

    final ArrayList<String> foodList = new ArrayList<String>();        
    foodList.addAll(Arrays.asList("Apple", "Squash", "fruits"));

    // Check if items from foodList exist in the keyset of productsMap

    for(String item : foodList){
        if(productsMap.containsKey(item)){
            System.out.println("productsMap contains a key named " + item);
        } else {
            System.out.println("productsMap doesn't contain a key named " + item);
        }
    }

    // Check if items from foodList exits in productsMap's values

    for (Map.Entry<String, ArrayList<String>> entry : productsMap.entrySet()){

        System.out.println("\nSearching on list values for key " + entry.getKey() + "..");

        for(String item : foodList){
            if(entry.getValue().contains(item)){
                System.out.println("productMap's list under key " + entry.getKey() + " contains item " + item);
            } else {
                System.out.println("productMap's list under key " + entry.getKey() + " doesn't contain item " + item);
            }
        }      
    } 
}

结果如下:

productsMap 不包含名为 Apple 的键

productsMap 不包含名为 Squash 的键

productsMap 包含一个名为 fruits 的键

搜索关键水果的列表值..

productMap 的 key fruits 下的列表包含 Apple 项

productMap 的 key fruits 下的列表不包含 item Squash

productMap 的 key fruits 下的列表不包含 item fruits

搜索关键蔬菜的列表值..

productMap 在 key veggies 下的列表不包含 Apple 项

productMap 在 key veggies 下的列表包含项目 Squash

productMap 在 key veggies 下的列表不包含项目 fruits

于 2013-08-22T20:00:16.327 回答
1

尝试这个

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

    while(keySetIterator.hasNext()){
        String key = keySetIterator.next();
        if(valueSetIterator.next().contains(key)){    // corrected here
            System.out.println("Yes! its a " + key);
        }
}
于 2013-08-22T19:31:47.953 回答
1

如果你想要 Java 8 的方式,你可以这样做:

    private static boolean containsValue(final Map<String, ArrayList<String>> map, final String value){
    return map.values().stream().filter(list -> list.contains(value)).findFirst().orElse(null) != null;
}

或者是这样的:

    private static boolean containsValue(final Map<String, ArrayList<String>> map, final String value){
    return map.values().stream().filter(list -> list.contains(value)).findFirst().isPresent();
}

两者都应该产生几乎相同的结果。

于 2013-08-22T19:31:54.283 回答