Java - using Map how to find matching Key when Values are stored a List of strings

前端 未结 4 785
萌比男神i
萌比男神i 2021-01-24 01:10

All,

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

    Map> cat = new HashMap

        
4条回答
  •  爱一瞬间的悲伤
    2021-01-24 01:51

    You need to create the inversed map:

    Map fruitCategoryMap = new HashMap<>();
    for(Entry> catEntry : cat.entrySet()) {
        for(String fruit : catEntry.getValue()) {
            fruitCategoryMap.put(fruit, catEntry.getKey());
        }
    }
    

    Then you can simply do:

    String category = fruitCategoryMap.get("Banana"); // "Fruit"
    

提交回复
热议问题