How to traverse the values of a HashMap through a given key?

2

How can I go through the values of a HashMap through a given key?

An example to illustrate: I have a HashMap named values, with a key that is an id represented by String and a value that is an integer.

HashMap<String, Integer> valores = new HashMap<String,Integer>();

valores.put("Id01",13);
valores.put("Id02",4);
valores.put("Id01",37);
valores.put("Id01",49);
valores.put("Id02",9);
valores.put("Id01",78);
valores.put("Id03",5);
valores.put("Id01",90);

How do I, for example, loop / for to cycle through the HashMap and print all the HashMap values belonging to the "Id01" key? Generating the following result on console:
13 37 49 78 90

    
asked by anonymous 22.04.2015 / 21:58

2 answers

3

You are currently using HashMap incorrectly. For each key there is only one value (although the opposite is not true). So when you do this:

valores.put("Id01",13);
valores.put("Id01",37);

The only thing that will be worth is the last one, because for the key Id01 there can only be one value.

What you really want is that there can be multiple values for a key. And then what I think you want is one of four things:

  • Map<String, List<Integer>> - If each key value can have multiple integer values associated, and their order must be the same as they were entered and they can be repeated.
  • Map<String, Set<Integer>> or Map<String, SortedSet<Integer>> , where SortedSet<Integer> or Set<Integer> is TreeSet - If each value can have multiple integer values associated, and their order must be a growing order and they can not be repeated. / li>
  • Map<String, Set<Integer>> , where Set<Integer> is LinkedHashSet - If each value can have multiple integer values associated, and their order must be the same as they were inserted and they can not be repeated.
  • Map<String, Set<Integer>> , where Set<Integer> is HashSet - If each value can have multiple integer values associated, and their order does not matter and can be any one and they can not be repeated.
  • Another consideration to make is whether or not your Map can undergo changes after having all your initial data populated:

    • Putting this in code, you might want this:

      public void xx1() {
          Map<String, List<Integer>> valores = new HashMap<>(10);
          valores.put("Id01", Arrays.asList(13, 37, 49, 78, 50));
          valores.put("Id02", Arrays.asList(4, 9));
          valores.put("Id03", Arrays.asList(5));
      }
      

      In this code above, the order of the values is the same as they were entered and future changes are not very welcome.

    • Or this:

      public void xx2() {
          Map<String, List<Integer>> valores = new HashMap<>(10);
          valores.put("Id01", new ArrayList<>(Arrays.asList(13, 37, 49, 78, 50)));
          valores.put("Id02", new ArrayList<>(Arrays.asList(4, 9)));
          valores.put("Id03", new ArrayList<>(Arrays.asList(5)));
      }
      

      Already in this code, future changes are welcome, different from the first.

    • Or maybe this:

      public void xx3() {
          Map<String, Set<Integer>> valores = new HashMap<>(10);
          valores.put("Id01", new LinkedHashSet<>(Arrays.asList(13, 37, 49, 78, 50)));
          valores.put("Id02", new LinkedHashSet<>(Arrays.asList(4, 9)));
          valores.put("Id03", new LinkedHashSet<>(Arrays.asList(5)));
      }
      

      Here future changes are welcome, but reps are not allowed. The order of the numbers is the order in which they were inserted.

    • Or else this:

      public void xx4() {
          Map<String, Set<Integer>> valores = new HashMap<>(10);
          valores.put("Id01", new HashSet<>(Arrays.asList(13, 37, 49, 78, 50)));
          valores.put("Id02", new HashSet<>(Arrays.asList(4, 9)));
          valores.put("Id03", new HashSet<>(Arrays.asList(5)));
      }
      

      Here future changes are welcome, repetitions are not allowed, but the order of numbers does not matter.

    • Or this:

      public void xx5() {
          Map<String, Set<Integer>> valores = new HashMap<>(10);
          valores.put("Id01", new HashSet<>(10));
          valores.put("Id02", new HashSet<>(10));
          valores.put("Id03", new HashSet<>(10));
      
          valores.get("Id01").add(13);
          valores.get("Id02").add(4);
          valores.get("Id01").add(37);
          valores.get("Id01").add(49);
          valores.get("Id02").add(9);
          valores.get("Id01").add(78);
          valores.get("Id03").add(5);
          valores.get("Id01").add(90);
      }
      

      Here values are inserted one-by-one after Map has been created and reps are not allowed. The order of the values does not matter (if interested, just change new HashSet<>(10) by new LinkedHashSet<>(10) or new TreeSet<>() . Ideal for the case where Map will change after it has been created.

    • Or who knows this:

      public void xx6() {
          Map<String, List<Integer>> valores = new HashMap<>(10);
          valores.put("Id01", new ArrayList<>(10));
          valores.put("Id02", new ArrayList<>(10));
          valores.put("Id03", new ArrayList<>(10));
      
          valores.get("Id01").add(13);
          valores.get("Id02").add(4);
          valores.get("Id01").add(37);
          valores.get("Id01").add(49);
          valores.get("Id02").add(9);
          valores.get("Id01").add(78);
          valores.get("Id03").add(5);
          valores.get("Id01").add(90);
      }
      

      Similar to the above, but repetitions are allowed and the order of the numbers is the order in which they were inserted.

    • Or maybe even this, using Java 8:

      public BiFunction<String, List<Integer>, List<Integer>> add(int i) {
          return (k, v) -> {
              List<Integer> list = v != null ? v : new ArrayList<>(10);
              list.add(i);
              return list;
          };
      }
      
      public void xx7() {
          Map<String, List<Integer>> valores = new HashMap<>(10);
          valores.compute("Id01", add(13));
          valores.compute("Id02", add(4));
          valores.compute("Id01", add(37));
          valores.compute("Id01", add(49));
          valores.compute("Id02", add(9));
          valores.compute("Id01", add(78));
          valores.compute("Id03", add(5));
          valores.compute("Id01", add(90));
      }
      
    22.04.2015 / 23:04
    1

    Friend,

    Your HashMap concept is wrong. You will need to modify the data type (signature) of your HashMap.

    HashMap<String, Integer[]> valores = new HashMap<String,Integer[]>();
    

    After that, you can assign keys and values like this:

    valores.put("Id01",new Integer[]{13,37,49,78,90});
    valores.put("Id02",new Integer[]{4,9});
    valores.put("Id03",new Integer[]{5});
    

    Now just do the tie and the consistency:

    // vamos obter uma view dos mapeamentos
    Set set = valores.entrySet();
    
    // obtemos um iterador
    Iterator i = set.iterator();
    
    // e finalmente exibimos todas as chaves e seus valores
    while(i.hasNext()) {
        Map.Entry<String, Integer[]> entrada = (Map.Entry<String, Integer[]>)i.next();
        if (entrada.getKey().equals("Id01")) {
            for (Integer valor : entrada.getValue()) {
                System.out.println("Valor é: "+valor);
            }
        }
    }
    
        
    22.04.2015 / 22:40