Header Ad

HackerRank Java Map problem solution

In this HackerRank java Map problem in java programming language You are given a phone book that consists of people's names and their phone number. After that, you will be given some person's name as a query. For each query, print the phone number of that person.

HackerRank Java Map problem solution


HackerRank java map problem solution.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
      		try {
			int no_of_entries = 0;
			int i = 0;
			String name = null;
			int number = 0;
			String query = null;
			HashMap<String, Integer> phoneBook = new HashMap<String, Integer>();
			BufferedReader b = new BufferedReader(new InputStreamReader(
					System.in));
			no_of_entries = Integer.parseInt(b.readLine());			
			while (i < no_of_entries) {
				name = b.readLine();
				number = Integer.parseInt(b.readLine());
				phoneBook.put(name, number);
				i++;
			}
			while (!(query = b.readLine().trim()).isEmpty()) {
				if (phoneBook.containsKey(query))
					System.out.println(query + "=" + phoneBook.get(query));
				else
					System.out.println("Not found");
			}
		} catch (Exception e) {
			
		}
    }
}



Second solution

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());
        Map<String,String> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            String name = scanner.nextLine();
            String phone = scanner.nextLine();
            map.put(name, phone);
        }
        while (scanner.hasNextLine()) {
            String query = scanner.nextLine();
            if (map.containsKey(query)) {
                System.out.println(query + "=" + map.get(query));
            } else {
                System.out.println("Not found");
            }
        }
    }
}


A solution in java8 programming.

import java.util.*;
import java.io.*;

class Solution{
    public static void main(String []argh)
    {
        Map<String,Integer> name_ph = 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();
            name_ph.put(name,phone);
            in.nextLine();
        }
        while(in.hasNext())
        {
            String s=in.nextLine();
            System.out.println(name_ph.containsKey(s)?s+"="+name_ph.get(s):"Not found");
        }
    }
}

Post a Comment

0 Comments