Passing map to method

Asked

Viewed 31 times

0

I am a beginner in Java and I have done some little projects as tests.

In this case, I’ve been reading and found interesting the map, but, I was upset when it came to applying. I thought it would be a good example for me to familiarize myself with. Could you help me how this implementation would be?

private TesteCiclo buildTesteCiclo(Map<String, String> map, DateService dateService) {
    String id = map.get("id");
    long idCiclo = Long.parseLong(map.get("id_ciclo"));
    String descricao = map.get("descricao");
    String servico = map.get("servico");
    Long valorCobranca = obtemValorDaCobranca(descricao, id, idCiclo);
    return EventosMap.buildTesteCiclo(id, idCiclo, descricao, servico,dateService, valorCobranca);
}

1 answer

0

Map is different from a list itself, because instead of having numeric indices (like in a vector) you can have an index of any type. As its name says Map will map each key for a value. I will illustrate:

With a vector you would have:

String[] vet = new String[]{"ola", "bom dia"};
System.out.println(vet[0]) // vai imprimir 'ola'
System.out.println(vet[1]) // vai imprimir 'bom dia'

Now with map:

Map<Integer, String> map = new HashMap<>();
map.put(0, "ola");
map.put(1, "bom dia");

The two structures are equivalent, map.get(0) will print the same as vet[0] and so on. The nice thing about Map is that you can use any type of object as an index, in your example a String. This index, as in vectors, is unique.

If you have:

Map<String, String> map = new HashMap<>();
map.put("Nome", "Joao");
map.put("Sobrenome", "Teste");

It’s like you’ve got

map["Nome"] = "João";

But if you do:

map.put("Nome", "Joao");
map.put("Nome", "Ola");

in this case you will overwrite the value associated with the key Nome.

I hope you understand the idea of Map. Hug

  • Great explanation. Thank you very much!

  • thank you, mark the answer as accepted

Browser other questions tagged

You are not signed in. Login or sign up in order to post.