简体   繁体   中英

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.

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        
}

You said:

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

To prevent the second entry attempt from overwriting the first entry in a Map , use Map::putIfAbsent in Java 8 and later.

Map<String, Integer> wordIndex = new LinkedHashMap<>();
wordIndex.putIfAbsent("The", 0);
wordIndex.putIfAbsent("Hello", 6);
wordIndex.putIfAbsent("Katherine", 17);
wordIndex.putIfAbsent("Hello", 21);

wordIndex.entrySet().forEach(System.out::println);

Prints

The=0
Hello=6
Katherine=17

The Map.putIfAbsent will only the first values entered will be retained. We can see the first ("Hello", 6) entry survived, and the second ("Hello", 21) entry attempt failed and was discarded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM