Search code examples
javahashmap

How do I remove duplicates in a Linked HashMap?


I'm creating a Linked HashMap that will read a string and integer from the user inputs. It is set up like this:

LinkedHashMap<String, Integer> wordIndex = new LinkedHashMap<String, Integer>();

My goal is to remove any duplicates the user may enter. Here is an example:

wordIndex.put("The", 0);
wordIndex.put("Hello", 6);
wordIndex.put("Katherine", 17);
wordIndex.put("Hello", 21);

I want to keep the first "Hello" and remove the second one.

This is my first time using Linked HashMaps, and thus, I am unfamiliar with the built-in functions that are at my disposal. Is there a function for HashMaps that can allow me to check the wordIndex HashMap one by one to look for duplicates every time a new value & key is entered? If not, what process can I use to check for duplicates individually? Thank you for your help.


Solution

  • The default behavior will Override the existing value with the existing key, So in the LinkedHashMap has the following values

    {The=0, Hello=21, Katherine=17}
    

    , And you can check if the key is already exists using containsKey()

    if (wordIndex.containsKey("Hello")) {
        // do something        
    }