How to banking corporation tally if a primal exists inwards HashMap Java? Use containsKey()

One of the mutual programming project acre using HashMap inwards Java is to banking concern check if a given telephone 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 telephone the containsKey() method, it returns truthful if given telephone commutation exists inwards HashMap, otherwise false; only I convey seen many programmer's codes similar nosotros volition encounter inwards this article, which prompted 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 move if you lot convey added zip values into HashMap, squall back HashMap does permit zip values. Many programers volition essay this code for approximately input together with think that it's working fine, solely to exercise a subtle põrnikas inwards production.  It's ever improve to role an API method if it tin exercise the job, many greats convey advised this. Joshua Bloch fifty-fifty included a chapter on his classic mass Effective Java, a must-read mass for whatever Java programmer.



How to banking concern check if a telephone commutation exists inwards HashMap inwards Java

Here is our sample programme to demonstrate how you lot tin role containsKey() method to check if a given telephone commutation exists inwards HashMap or not. In this example, nosotros convey showtime created a HashMap amongst values using double twosome initialization technique. Later, I convey asked the user to larn into a telephone commutation inwards ascendency prompt.



Our programme reads input from the command prompt using Scanner class together with uses containsKey() to banking concern check if given telephone commutation exists or not. If the telephone commutation exists together with hence this method volition provide truthful otherwise false.

import java.util.HashMap; import java.util.Map; import java.util.Scanner;  /**  * Java Program to to banking concern 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 larn into a telephone commutation to banking concern 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 larn into a telephone commutation to banking concern check inwards Map? 101 Congrats, given telephone commutation exists inwards Map

You tin encounter that containsKey() method has returned truthful for existing key. If you lot move past times whatever telephone commutation which is non introduce inwards Map together with hence this method volition provide false. If you lot expect at the code of this method from HashMap.java cast on JDK, you lot volition abide by that it expect for an entry object corresponding to the given key, which agency it too handles zip values. 

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

You tin role this technique to verify if a telephone commutation exists or non inwards whatever Map e.g. 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. 

Here is a diagram which shows how HashMap is structured internally on an array, called bucket. When you lot telephone telephone get() method, it gets the bucket place past times applying a hash portion on telephone commutation together with and hence banking concern check if an entry is stored in that place or not, if no entry together with hence it returns null, which agency telephone commutation doesn't be inwards Map. If in that place is an entry together with hence it retrieve the value from it together with provide that. Though it's too possible that in that place are multiple entries inwards that bucket place due to the hash collision, inwards that case, it goes through all entries to abide by the correct one. So it's far from easy, encounter my postal service how get() together with put() industrial plant inwards Java, for a detailed tidings on this topic. 

 One of the mutual programming project acre using HashMap inwards Java is to banking concern check if a given telephone commutation How to banking concern check if a telephone commutation exists inwards HashMap Java? Use containsKey()


That's all nigh how to banking concern check if a telephone commutation exists inwards HashMap inwards Java or not. You tin too role containsValue() method to banking concern check if given value exists inwards Map or not. Similarly, this technique tin too move used to banking concern check if a given telephone commutation is introduce or non inwards whatever Map implementation.

Further Learning
Java Fundamentals: Collections
From Collections to Streams inwards Java 8 Using Lambda Expressions
Grokking Algorithms past times Aditya Bhargava
Java Programming Interview Exposed past times Makham

Subscribe to receive free email updates:

0 Response to "How to banking corporation tally if a primal exists inwards HashMap Java? Use containsKey()"

Posting Komentar