Jay Desai Jay Desai - 1 month ago 7
Java Question

Checking variable value with hashmap data in java

I need to check my variable value directly with hashmap values.

My hashmap values has two entry both in string and I need to check my variables value with first entry of hashmap.

Smaller version of code is above.

HashMap<String , String> directory = new HashMap<String , String>();
directory.put("AFG","Afghanistan");
directory.put("GBR","United Kingdom of Great Britain and Northern Ireland");
directory.put("IDN","Indonesia");
directory.put("IND","India");


Next i have used scanner class to get user's value.Then what i need to know is how to compare this user's value with first entry of hashmap that is i.e AFG , GBR , etc

Sample code of whole program is :

import java.util.*;

public class hashmapdemo {
public static void main(String args[]) {

HashMap<String , String> directory = new HashMap<String , String>();
directory.put("AFG","Afghanistan");
directory.put("GBR","United Kingdom of Great Britain and Northern Ireland");
directory.put("IDN","Indonesia");
directory.put("IND","India");

Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println(name);

// comparing logic ?

}
}

Answer

First, to prevent a nullPointer exception you want to make sure your HashMap contains the users input key with:

directory.containsKey(key)

if that is successful then you can return that value of the corresponding key:

return directory.get(key);

String key = sc.nextLine();


       if(directory.containsKey(key))
       {
           return directory.get(key);
       }