How To Banking Concern Agree If A Commutation Object Exists Inwards Hashmap Java? Containskey() Example

Hello guys, y'all powerfulness know that i of the mutual programming tasks land using HashMap inwards Java is to depository fiscal establishment check if a given telephone commutation exists inwards the map or not. This is supposed to endure easy, right? Yes, it is slowly if y'all know your API well, all y'all demand to is telephone yell upward the containsKey() method, it returns true if given telephone 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 spider web log post.

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

This code is fragile, it volition non operate if y'all convey added null values into HashMap because HashMap does allow naught values.

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

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

The biggest wages of using an API method is that it has already tried together with tested past times many programmers together with faced many inputs together with weather which is impossible for your ain code to execute. This exercise goodness of testing exposure actually helps when y'all position your code into production.

I also propose all programmers become through a comprehensive mass or class 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 improve way to exercise things.




How exercise HashMap checks if a telephone commutation object exists or not

Here is a diagram which shows how HashMap is structured internally on an array, called bucket. When y'all call get() method, it gets the bucket place past times applying a hash component on telephone commutation together with therefore depository fiscal establishment check if an entry is stored at that topographic point or not, if no entry therefore it returns null, which agency telephone commutation doesn't be inwards Map.

If at that topographic point is an entry therefore 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 honor the right one.

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

double brace initialization technique, it's an anti-pattern but y'all tin flame role it if your Map is non likewise big. Later, I convey asked the user to come inwards a telephone commutation inwards ascendence prompt, which y'all tin flame depository fiscal establishment check against this HashMap.

Our plan reads input from the command prompt using Scanner class together with uses containsKey() to depository fiscal establishment check if a given telephone commutation exists or not.  If the telephone commutation exists therefore this method volition provide true otherwise it volition return false. Accordingly, our plan volition impress whether a given telephone commutation exists inwards the HashMap or not.

import java.util.HashMap; import java.util.Map; import java.util.Scanner;  /**  * Java Program to to depository fiscal establishment check if a telephone commutation exists inwards HashMap or not.   * This illustration uses containsKey() method to search for a telephone 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 telephone commutation exists inwards Map         Scanner scnr = new Scanner(System.in);          System.out.println("Please come inwards a telephone commutation to depository fiscal establishment check inwards Map?");         int telephone commutation = scnr.nextInt();          // checking if telephone commutation exists inwards HashMap         if (idToName.containsKey(key)) {             System.out.println("Congrats, given telephone commutation exits inwards Map");         } else {             System.out.println("Sorry, given telephone commutation doesn't exists inwards Map");         }                 scnr.close();      }  }  Output : {101=Johnny, 102=Root, 103=Shane} Please come inwards a telephone commutation to depository fiscal establishment check inwards Map? 101 Congrats, given telephone commutation exists inwards Map

You tin flame run across that containsKey() method has returned true for an existing key. If y'all move past times whatever telephone commutation which is non acquaint inwards Map therefore this method volition provide false.

If y'all hold off at the code of this method from HashMap.java shape on JDK, y'all volition honor 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 flame role this technique to verify if a telephone 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 nigh how to depository fiscal establishment check if a telephone commutation exists inwards HashMap inwards Java or not. You tin flame also role containsValue() method to depository fiscal establishment check if given value exists inwards Map or not. Similarly, this technique tin flame also endure used to depository fiscal establishment check if a given telephone commutation is acquaint or non inwards whatever Map implementation similar TreeMap, LinkedHashMap, Hashtable, EnumMap etc.

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

Thanks for reading this article therefore far. If y'all similar this article therefore delight part amongst your friends together with colleagues. If y'all convey whatever interrogation or feedback therefore delight driblet a comment

0 Response to "How To Banking Concern Agree If A Commutation Object Exists Inwards Hashmap Java? Containskey() Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel