Java - 使用Map如何在存储值时找到匹配的键字符串列表 [英] Java - using Map how to find matching Key when Values are stored a List of strings

查看:845
本文介绍了Java - 使用Map如何在存储值时找到匹配的键字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部

我有一个类别和子类别的地图,如下所示:

I have a map with categories and subcategories as lists like this:

    Map<String,List<String>> cat = new HashMap<String,List<String>>();

    List<String> fruit = new ArrayList<String>();
    fruit.add("Apple");
    fruit.add("Pear");
    fruit.add("Banana");

    cat.put("Fruits", fruit);

    List<String> vegetable = new ArrayList<String>();
    vegetable.add("Carrot");
    vegetable.add("Leak");
    vegetable.add("Parsnip");

    cat.put("Vegetables", vegetable);

我想查找胡萝卜是否在地图中,哪个键(水果)它匹配,但是:

I want to find if "Carrot" is in the map and to which key ("Fruit') it matches, however:

    if (cat.containsValue("Carrot")) {System.out.println("Cat contains Leak");}

将False作为结果,如何匹配胡萝卜键值蔬菜

gives False as outcome. How can I match "Carrot" and get back the key value "Vegetable"

Thx。

推荐答案

钥匙,并检查值,如果发现,然后打破循环。

Iterate thought all the keys and check in the value if found then break the loop.

for (String key : cat.keySet()) {
    if (cat.get(key).contains("Carrot")) {
        System.out.println(key + " contains Carrot");
        break;
    }
}

这篇关于Java - 使用Map如何在存储值时找到匹配的键字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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