1

I met a problem about doing operation between a lambda parameter and a int. Codes are written as follows:

HashMap<Integer, Integer> testMap = new HashMap<>();
testMap.put(1, 1);
testMap.put(2, 2);
testMap.entrySet().removeIf((key, value) -> value < 100);

IDEA shows an error of Operator '<' cannot be applied to '<lambda parameter>', 'int'.
I am wondering why and if there is any way to fix the problem.

knittl
  • 246,190
  • 53
  • 318
  • 364
NormalLLer
  • 183
  • 2
  • 11
  • 1
    The type of your lambda should be Predicate>, not something with two parameters. – tgdavies May 21 '22 at 07:56
  • 2
    `testMap.entrySet().removeIf(e -> e.getValue() < 100);`. Or depending on preference: `testMap.values().removeIf(v -> v < 100);`. The `removeIf` method of the entry set needs a `Predicate super Entry>`, so before `->` you need to place one entry, not key and value separately. – Ole V.V. May 21 '22 at 07:56

1 Answers1

3

Map#entrySet returns a Set<Map.Entry<K,V>>. Set inherits removeIf from the Collection interface, which expects a Predicate<? super E>, namely a predicate with a single argument. E in this case is Map.Entry<K,V> (which is still only a single object, even though it holds two other values: a key and a value). Key and value can be accessed via getKey() and getValue() methods, respectively.

Your code is fixed easily:

testMap.entrySet().removeIf(entry -> entry.getValue() < 100);
knittl
  • 246,190
  • 53
  • 318
  • 364