Home > other >  Checking the existence of the key before adding a newhashmap
Checking the existence of the key before adding a newhashmap

Time:01-10

I would like to check if the key already exists before adding an item to the Hashmap. Adds keys from 1 to 20k to the Hashmap, and some may repeat themselves. I would like to check if the key I want to add already exists, if so, I write it to the screen, for example. I know that you can check if such a key exists with the containsKey method, but I have no idea how to refer to the previous element.

I have absolutely no idea how to start this because I'm just getting started with beanshell :/ Thanks in advance for your help :D

 Map MAP_SA = new HashMap()
    
    while(iterator.hasNext()){
    org = iterator.next();
    MAP_SA.put(org.getExtended8(),org.getName());
    //here I would like to check if the key repeats before adding anything to the map
    }

CodePudding user response:

Assumption:

Keys in Maps are unique, so if you try to insert a new record with a key already present, there will be a "collision" and the value corresponding to that key in the map will be overwritten.

Answering your question: containsKey() is the correct way, especially in your case where you do a check at runtime, you have the possibility to check at each iteration if the current value you want to insert is already present in the whole map, because containsKey() goes to probe all the keys in the map.

Map MAP_SA = new HashMap()
    
    while(iterator.hasNext()){
    org = iterator.next();

    if(!MAP_SA.containsKey(org.getExtended8())){ // check all over the map
      MAP_SA.put(org.getExtended8(),org.getName());
    }else
      System.out.println("Error: the key already exists");

    }

CodePudding user response:

You can also use the putIfAbsent method on Map interface (available as from JDK 8) which, as the name indicates it, will only add the value only if the specified key does not exist yet.

  •  Tags:  
  • Related