2

I'm trying to increment of value in hashmap. I'm using Java 8 and Netbeans, so wrote this code:

Map<P, Integer>color_match_hash = new HashMap<P, Integer>();
for(int k=0; k<color_match_hash.size(); k++){
if(color_match_hash.get(k).equals(P_Color.get(i))){
    color_match_hash.merge(color_match_hash.get(k), 1, Integer::sum);
}

}

P is an object with 5 Integers. It is a simple algorithm, in which I want to increment value of key (k) and I got "incompatible types: Integer cannot be converted to P". What I'm doing wrong? I must add that I tried a lot of ways to increment this and in every I had the same message. Most efficient way to increment a Map value in Java

Karola
  • 29
  • 4

1 Answers1

1

You have created a HashMap with key of type P and value of type Integer.

First of all, you are iterating the map like we do for a list or array.

Secondly, this is a wrong usage - color_match_hash.get(k). The get method expects a value having a data type P (the key).

You can read How to efficiently iterate over each entry in a Java Map?, to see different ways to iterate over a map.

uneq95
  • 2,158
  • 2
  • 17
  • 28