I was getting type mismatch errors, until I refactored code to this:
public final Stream<Map.Entry<E, Integer>> orderedStreamOfEntries() {
return this.m_map.entrySet()
.stream()
.sorted(Comparator.comparingInt(Entry::getValue))
.map(AbstractMap.SimpleImmutableEntry::new);
}
- The return type is
Stream<Entry<E, Integer>>
- The type of the stream at the end of this routine is
Stream<SimpleImmutableEntry<E, Integer>>
The formal type parameter E
has this definition:
<E extends Enum<E> & MyCustomInterface>
I don't understand why this appears to be acceptable to the compiler. Because Java generics are invariant, even though java.util.AbstractMap.SimpleImmutableEntry
implements java.util.Map.Entry
, I would have said that Stream<SimpleImmutableEntry<>>
is not a subtype of the return type, Stream<Entry<>>
.