How to go through the values of a Hashmap through a certain key?

Asked

Viewed 3,012 times

2

How can I traverse the values of a Hashmap through a certain key?

An example to illustrate: I have a Hashmap called 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 across the Hashmap and print all Hashmap values belonging to the "Id01" key? Generating the following result on the console:
13 37 49 78 90

  • 1

    How, since it is not possible to have multiple equal keys in one HashMap?

  • So I didn’t know. Thank you.

2 answers

3


Are you using the HashMap incorrectly. For each key there is only one value (although otherwise it is not true). So when you do this:

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

The only one that’s gonna count is the last one, because for the key Id01 there can be only one value.

What you really want is for there to be multiple values for a key. And so what I think you want is one of these four things:

  1. Map<String, List<Integer>> - If each key value can have multiple integer values associated, and their order should be the same as the one they were entered into and they can repeat themselves.
  2. Map<String, Set<Integer>> or Map<String, SortedSet<Integer>>, where the SortedSet<Integer> or Set<Integer> is a TreeSet - If each value can have multiple integer values associated, and their order should be an ascending order and they cannot be repeated.
  3. Map<String, Set<Integer>>, where the Set<Integer> is a LinkedHashSet - If each value can have multiple integer values associated, and the order of them must be the same in which they were inserted and they cannot be repeated.
  4. Map<String, Set<Integer>>, where the Set<Integer> is a HashSet - If each value can have multiple integer values associated, and their order does not matter and it can be any one and they cannot be repeated.

Another consideration to make is whether this yours Map may or may not change after you have all your initial data populated:

  • Putting this in code, maybe you 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 values is the same in which they were inserted 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)));
    }
    

    In this code, future changes are very welcome, different from the first case.

  • 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 repeats 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 the 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 entered one-by-one after the Map created and repeats are not allowed. The order of values does not matter (if interested, just change the new HashSet<>(10) for new LinkedHashSet<>(10) or new TreeSet<>(). Ideal for the case where the Map will undergo changes after it has been created.

  • Or who knows that:

    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 previous, but repeats are allowed and the order of the numbers is the order in which they were inserted.

  • Or maybe even that, 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));
    }
    
  • 1

    You helped me a lot. Thank you! It was not really clear the concept of Hashmap for me and the alternatives expanded the possibilities.

1

Friend,

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

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

After that, you can assign keys and values in this way:

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 make the loop 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);
        }
    }
}

Browser other questions tagged

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