1

I've created a loop which goes through my HashMap. Then I check whether the name of the current key (A) is equal to the key that might be added (B). The hash codes of key A and key B aren't necessarily equal when their names are. Therefore I check whether they are equal by transforming them into a string (with override of .equals()). The code is working but there most be a cleaner and easier way to do this.

This is my current code:

for (HashMap.Entry<Identifier, SetInterface<BigInteger>> entry : idAndSet.entrySet()) {
    if (entry.getKey().isEqual(identifier)) {
        factor = entry.getValue();
        return factor;
    }  
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99

2 Answers2

0

You could misuse the Map.computeIfPresent method.

factor = map.computeIfPresent(identifier, (k,v) -> v);
return factor;

The method returns the value associated with the specified key, or null if none

Eritrean
  • 15,851
  • 3
  • 22
  • 28
0

The hash codes of key A and key B aren't necessarily equal when their names are.

That is not a good idea. Any class that acts as a key should override equals and hashCode. And it would be a good idea to make the class immutable as well (otherwise you could end up with some difficult debugging to do).

Once you do that, you can just do


   Map<Indentifer, Object> map...;
   Object value = map.get(id);

   // or as of Java 8+

   Object value = map.getorDefault(id, someDefaultValue);

WJS
  • 36,363
  • 4
  • 24
  • 39