DEV Community

Beatriz Maciel
Beatriz Maciel

Posted on

5 3

HackerRank #30 | Map | 🇧🇷

Este problema pede para que, a partir de uma lista telefônica, seja inserido um número e retorne a mesma quantidade de contatos relativo à esse número.

O código começa assim:

//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();
        for(int i=0;i<n;i++)
        {
            String name=in.nextLine();
            int phone=in.nextInt();
            in.nextLine();
        }
        while(in.hasNext())
        {
            String s=in.nextLine();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

=========

O resultado final é:

package com.possible.map;

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

public class Solution {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(new File("input.txt"));
        int n = in.nextInt(); // quantidade de contatos que vc quer
        in.nextLine();
        HashMap<String,Integer> listaTelefonica = new HashMap<>();

        for (int i = 0; i < n; i++) {
            String name = in.nextLine(); // pega o nome
            int phone = in.nextInt(); // pega o telefone
            listaTelefonica.put(name, phone);
            in.nextLine();
        }

        while (in.hasNext()) {
            String s = in.nextLine();
            if(listaTelefonica.containsKey(s)) // se existir
                System.out.println(s + "=" + listaTelefonica.get(s));
            else
                System.out.println("Not found");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

=========

Referências

Map : Oracle
HashMap : Oracle
Map : DevMedia

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.