Using a map to store 1 ID for N values? [closed]

0

EDIT For lack of details, I've reset the question here . The question has been flagged and a moderator will delete it as soon as possible, thanks.

I have the following IDs and values, respectively:

1 - 18;
1 - 19;
1 - 20;
3 - 21;
3 - 22;
8 - 23;
8 -24;
8 - 25;
11 - 26;
3 - 27;
3 - 28;

How can I do that, when I pass the ID value via parameter, it returns me the values of this ID? For example, if I passed ID 3, it would return the values 21, 22, 27 & 28.

I should use map <integer, List<Integer>> , correct? But how can I do this? How would I also add these values into my List?

    
asked by anonymous 22.05.2015 / 21:02

2 answers

1

You can use HashMap .  It does the following:

  HashMap<Integer,ArrayList<Integer>> map=new HashMap<Integer,ArrayList<Integer>>();  
      //  chave = 3  ,  {1,22,27,28}
   map.put(3, new ArrayList<Integer>(Arrays.asList(1,22,27,28)));
   System.out.println( "Valores : " + map.get(3));
   // Resultado = "Valores : [1, 22, 27, 28]"

Where 3 is the key, just change the key and start a new Integer ArrayList

    
22.05.2015 / 21:18
0

Follow the logic to manage the map, to get the value just use get by passing the id. Any questions about the code just ask.

Map<integer, List<Integer>> map  = new HashMap<integer, List<Integer>>();

public void adicionar(Integer id, Integer elemento){
  if(map.containsKey(id)){
     map.get(id).add(elemento);
  }else{
     List<Integer>> lista = new ArrayList();
     lista.add(elemento);
     map.put(id,lista);
  }
}
    
22.05.2015 / 21:21