Home > Software design >  "Operator '<' cannot be applied to '<lambda parameter>', 'int
"Operator '<' cannot be applied to '<lambda parameter>', 'int

Time:05-21

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.

CodePudding user response:

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);
  • Related