Answering the question:
I want to know how to access each element of that list in the map
You must make two loops, one that goes through all the elements of your Map and another that goes through all the elements of the List, which is inside your Map.
I created a compileable example that demonstrates something similar to your original question and answering your question that is in the comment:
import java.util.*;
class Carteira {
private int num;
public void setNum(int num) { this.num = num; }
public int getNum() { return this.num; }
@Override
public String toString() { return "Valor da carteira: " + num; }
}
public class TesteHash {
public static void main(String[] args) {
Map<String, List<Carteira>> filter = new HashMap<>();
List<Carteira> carteiras = new ArrayList<>();
Carteira carteira1 = new Carteira();
Carteira carteira2 = new Carteira();
carteira1.setNum(10);
carteira2.setNum(15);
carteiras.add(carteira1);
carteiras.add(carteira2);
filter.put("carteiras", carteiras);
buscarCarteiras(filter);
}
public static void buscarCarteiras(Map<String, List<Carteira>> param) {
//aqui responde a sua dúvida
for(Map.Entry<String, List<Carteira>> entry: param.entrySet()) {
for(Carteira c: entry.getValue()) {
//na variavel `c` vc tem um objeto carteira
System.out.println(c);
}
}
}
}
Note that the first for
will execute only once, because within the variable param
has only a couple of values "carteiras"
, carteiras
.
The second for
will be executed twice, as it goes through the entire list that is inside the Map, and inside this list has two objects of type Carteira
. Inside this for it will print the value that returns from the method toString()
class Carteira
.
Can you explain it better with a code example? By the way, the code is Java or C#?!
– bfavaretto
The code is in java. I will try to explain my question better.
– Johnatan Dantas
filter.put("carteiras", carteiras)
you are trying to put a list of wallets where should be a Wallet object, or the Map statement should have beenMap<String, List<Carteira>> filter = new HashMap<>();
2) what other class? how do you want to call a method of another class? 3)Como faço para pegar o objeto carteira1
which criterion you want to use to know which element Voce wants to take? maybe Voce wants to pass the object portfolio as argument to the methodbuscarCarteira()
tb?– Math
i already manage to pass as parameter the list inside the map and already get to the method, it is coming the values correctly, only I want to know how to access each element of that list that is in the map.
– Johnatan Dantas
param.get("carteiras").containsKey(carteira1)
– Johnatan Dantas
that’s my question, I don’t know how to pick up the value inside that list.
– Johnatan Dantas