Friday, November 1, 2019

How To Banking Concern Represent If A Primal Object Exists Inward Hashmap Java? Containskey() Example

Hello guys, you lot mightiness know that 1 of the mutual programming tasks spell using HashMap inwards Java is to cheque if a given commutation exists inwards the map or not. This is supposed to move easy, right? Yes, it is slow if you lot know your API well, all you lot demand to is telephone phone the containsKey() method, it returns true if given commutation exists inwards HashMap, otherwise false; but I convey seen many programmers write code similar below which is non correct, which inspired me to write this weblog post.

if(map.get(key) !=  null){
    System.out.println("key exits inwards Map");
}

This code is fragile, it volition non operate if you lot convey added null values into HashMap because HashMap does allow cypher values.

Many Java programmers volition essay this code for about valid input together with think that it's working fine, solely to practise a subtle põrnikas inwards production.  That's why it's e'er ameliorate to write extensive JUnit tests for your code to essay positive, negative together with boundary conditions.

Another proposition I desire to brand is that it's e'er ameliorate to purpose an API method if it tin practise the job, non but me but many greats convey also advised this. The nifty Java programmer Joshua Bloch fifty-fifty included a chapter on this on his all-time nifty Java mass Effective Java, a must-read mass for whatever Java programmer.

The biggest payoff of using an API method is that it has already tried together with tested yesteryear many programmers together with faced many inputs together with atmospheric condition which is impossible for your ain code to execute. This practise goodness of testing exposure actually helps when you lot set your code into production.

I also advise all programmers acquire through a comprehensive mass or course of report similar The Complete Java Masterclass on Udemy to fill upward the gaps inwards your learning because Java is vast together with at that topographic point is e'er a ameliorate way to practise things.




How practise HashMap checks if a commutation object exists or not

Here is a diagram which shows how HashMap is structured internally on an array, called bucket. When you lot call get() method, it gets the bucket place yesteryear applying a hash business office on commutation together with and thence cheque if an entry is stored at that topographic point or not, if no entry together with thence it returns null, which agency commutation doesn't be inwards Map.

If at that topographic point is an entry together with thence it retrieves the value from it together with returns that. Though it's also possible that at that topographic point are multiple entries inwards that bucket place due to the hash collision, inwards that case, it goes through all entries to honour the right one.

So it's far from easy, sees my post how does get() together with put() industrial plant inwards Java, for a detailed give-and-take on this topic. 

double brace initialization technique, it's an anti-pattern but you lot tin purpose it if your Map is non every bit good big. Later, I convey asked the user to move into a commutation inwards ascendence prompt, which you lot tin cheque against this HashMap.

Our programme reads input from the command prompt using Scanner class together with uses containsKey() to cheque if a given commutation exists or not.  If the commutation exists together with thence this method volition furnish true otherwise it volition return false. Accordingly, our programme volition impress whether a given commutation exists inwards the HashMap or not.

import java.util.HashMap; import java.util.Map; import java.util.Scanner;  /**  * Java Program to to cheque if a commutation exists inwards HashMap or not.   * This illustration uses containsKey() method to search for a commutation inwards HashMap.  *  * @author WINDOWS 8  */ public class KeySearchDemo {      public static void main(String args[]) {          // our sample map          Map<Integer, String> idToName = new HashMap<Integer, String>() {             {                 put(101, "Johnny");                 put(102, "Root");                 put(103, "Shane");             }         };          System.out.println(idToName);          // checking if a commutation exists inwards Map         Scanner scnr = new Scanner(System.in);          System.out.println("Please move into a commutation to cheque inwards Map?");         int commutation = scnr.nextInt();          // checking if commutation exists inwards HashMap         if (idToName.containsKey(key)) {             System.out.println("Congrats, given commutation exits inwards Map");         } else {             System.out.println("Sorry, given commutation doesn't exists inwards Map");         }                 scnr.close();      }  }  Output : {101=Johnny, 102=Root, 103=Shane} Please move into a commutation to cheque inwards Map? 101 Congrats, given commutation exists inwards Map

You tin encounter that containsKey() method has returned true for an existing key. If you lot move yesteryear whatever commutation which is non introduce inwards Map together with thence this method volition furnish false.

If you lot expect at the code of this method from HashMap.java course of report on JDK, you lot volition honour that it looks for an entry object corresponding to the given key, which agency it also handles null values properly. 

 public boolean containsKey(Object key) {         return getEntry(key) != null;   }

You tin purpose this technique to verify if a commutation exists or non inwards whatever Map like. HashMap, TreeMap, together with LinkedHashMap. Why? because this method is defined inwards java.util.Map interface together with every map implementation are supposed to implement it.


That's all close how to cheque if a commutation exists inwards HashMap inwards Java or not. You tin also purpose containsValue() method to cheque if given value exists inwards Map or not. Similarly, this technique tin also move used to cheque if a given commutation is introduce or non inwards whatever Map implementation similar TreeMap, LinkedHashMap, Hashtable, EnumMap etc.

Further Learning
The Complete Java Masterclass
tutorial)
The divergence betwixt HashMap together with LinkedHashMap inwards Java? (answer)
The divergence betwixt Hashtable together with HashMap inwards Java? (answer)
The divergence betwixt HashMap together with ConcurrentHashMap inwards Java? (answer)
The divergence betwixt ArrayList together with LinkedList inwards Java? (answer)
The divergence betwixt Vector together with ArrayList inwards Java? (answer)
Difference betwixt EnumMap together with HashMap inwards Java
The divergence betwixt HashSet together with TreeSet inwards Java? (answer)
How to take a key-value distich from HashMap inwards Java? (tutorial)
How to variety a HashMap yesteryear keys inwards Java 8? (tutorial)

Thanks for reading this article thence far. If you lot similar this article together with thence delight part amongst your friends together with colleagues. If you lot convey whatever query or feedback together with thence delight drib a comment

No comments:

Post a Comment