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

前端 未结 4 786
萌比男神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:45

    You have to search for the value in the entire map:

    for (Entry<String, List<String>> entry : cat.entrySet()) {
        for (String s : entry.getValue()) {
            if (s.equals("Carrot"))
                System.out.println(entry.getKey());
        }
    }
    
    0 讨论(0)
  • 2021-01-24 01:51

    You need to create the inversed map:

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

    Then you can simply do:

    String category = fruitCategoryMap.get("Banana"); // "Fruit"
    
    0 讨论(0)
  • 2021-01-24 01:52

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-24 01:59

    try this,

    for (Map.Entry<String, List<String>> entry : cat.entrySet()) {
            String names[] = entry.getValue().toArray(new String[entry.getValue().size()]);
            for (int i = 0; i < names.length; i++) {
                if (names[i].equals("Carrot")) {
                    System.out.println("found"+names[i]);
                    break;
                } 
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题