Given snippet:
Map map1 = new HashMap<>();
map1.entrySet().stream().forEach(entry -> {
System.out.println(entry.getKey() + ":" + entry.getValue());
});
Without declaring generic types I get a compilation errors generally saying that entry
in forEach
is an Object type and not a Map.Entry
.
If I add generics (either Object
or ?
), it compiles just fine:
Map<Object,Object> map2 = new HashMap<>();
map2.entrySet().stream().forEach(entry -> {
System.out.println(entry.getKey() + ":" + entry.getValue());
});
Map<?,?> map3 = new HashMap<>();
map3.entrySet().stream().forEach(entry -> {
System.out.println(entry.getKey() + ":" + entry.getValue());
});
Same compilation error when calling other Stream
's API methods like filter
, map
, ...
Why missing generics makes compilation errors?