Hackerrank Java Map Solution
1 min read

Hackerrank Java Map Solution

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");
            }
        }
    }
}



Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×