Search code examples
javahashmapmultimap

MultiMap with Collection<String>


I am working on an XML file. In my XML file, there are somes nodes which have childs. This XML file has multiple tags.

<Cat categorie="CAT 1" guid="e9fdsd8ff">
    <!--Electric energie management-->
    **<item Var="VAR1" guid="2795ddsd410d">
        <desc> Energie Smart Management 
        </desc>
        <App guid="240adsqsd" />
        <App guid="90dqddqsq" />**
    </item>
</Cat>

Like you can see, my node "item " has the argument VAR=var1 and has 2 childs. So I created a hashMap to put, for 1 node his childs like below

private Map<String, Collection <String >> multiMap = new HashMap <> ();

So I Have something like that actually : [Key=Var1, Value = [gui0,guid1,...]]

Now, I would like to know if you knew how to verify if a guid is contained in a collection associated with a key in order to retrieve this key.

For example, if I have this String : 240adsqsd. I want to recover Var1.

Thanks for your help


Solution

  • It is possible. Say you have the key myKey and you want to know if the string mySearchString is contained in the collection behind that key.

    multiMap.get("myKey").contains("mySearchString");
    

    It will return true if mySearchString equals (case sensitive) any object in the colelction.

    You have to be careful though, the method contains on a collection uses the case sensitive equals method and will only work when they are 100% equal. So when your collection contains something like "MYSEARCHstring", it won't work, as well as "The sentence that contains mySearchString".

    EDIT:
    (Thanks Nikolas and Dici)
    Here a more complete example how to achieve that.

    String mySearchString = "mySearchString";
    Map<String, Collection<String>> multiMap = new HashMap<>();
    for (String key : multiMap.keySet()) {
        if (multiMap.get(key) != null && multiMap.get(key).contains(mySearchString)) {
            return key;
        }
    }
    

    If you don't know the key, you have to iterate over your map, check if one of the collections contains the searched string and then, when you found the collection (and its key) return the key.