Hackerrank Java Map Solution
Solution in java8
Approach 1.
//Complete this code or write your own from scratch
import java.util.*;
import java.io.*;
class Solution{
public static void main(String []argh)
{
Map<String, Integer> mp = new HashMap<>();
Scanner in = new Scanner(System.in);
int n=in.nextInt();
in.nextLine();
for(int i=0;i<n;i++)
{
String name=in.nextLine();
int phone=in.nextInt();
in.nextLine();
mp.put(name, phone);
}
while(in.hasNext())
{
String s=in.nextLine();
if(mp.containsKey(s))
System.out.println(s+"="+mp.get(s));
else
System.out.println("Not found");
}
}
}
Approach 2.
//Complete this code or write your own from scratch
import java.util.*;
import java.io.*;
class Solution{
public static void main(String []argh)
{
Scanner in = new Scanner(System.in);
int n=in.nextInt();
in.nextLine();
Map<String, Integer> map =new HashMap<>();
for(int i=0;i<n;i++)
{
String name=in.nextLine();
int phone=in.nextInt();
in.nextLine();
map.put(name , phone);
}
while(in.hasNext())
{
String s=in.nextLine();
if(map.containsKey(s)){
System.out.println(s+"="+ map.get(s));
}
else{
System.out.println("Not found");
}
}
}
}
Approach 3.
//Complete this code or write your own from scratch
import java.util.*;
import java.io.*;
class Solution{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
int n=in.nextInt();
in.nextLine();
HashMap<String, Integer> hash = new HashMap<String, Integer>();
for(int i=0;i<n;i++){
String name= in.nextLine();
int phone = in.nextInt();
hash.put(name,phone);
in.nextLine();
}
while(in.hasNext())
{
String s=in.nextLine();
try {
int temp = hash.get(s);
System.out.println(s+"=" + temp);
} catch (NullPointerException e) {
System.out.println("Not found");
}
}
}
}