I have a getMailBox method which returns a HashMap obtained by grouping values from a List<E>.
I need to override the get method so it doesn’t return null if the key is not found and return an empty List<T>.
When I do this, everything works and a map with an overridden method is returned
public Map<String, List<T>> getMailBox() {
Map<String, List<T>> tempMap = new HashMap<>() {
@Override
public List<T> get(Object key) {
Optional<List<T>> optional = Optional.ofNullable(super.get(key));
return optional.orElse(Collections.emptyList());
}
};
Map<String, List<T>> map = list.stream()
.collect(
java.util.stream.Collectors
.groupingBy(
Sendable::getTo,
java.util.stream.Collectors
.mapping(
Sendable::getContent,
java.util.stream.Collectors
.toList())));
tempMap.putAll(map);
return tempMap;
If I do this instead, it returns a map with a method not overridden and returns null if the key is not found.
public static class MailService<T> implements Consumer<Sendable <T>> {
private final List<Sendable<T>> list = new ArrayList<>();
public Map<String, List<T>> getMailBox() {
Map<String, List<T>> map = new HashMap<>() {
@Override
public List<T> get(Object key) {
Optional<List<T>> optional = Optional.ofNullable(super.get(key));
return optional.orElse(Collections.emptyList());
}
};
map = list.stream().collect(
java.util.stream.Collectors
.groupingBy(
Sendable::getTo,
java.util.stream.Collectors
.mapping(Sendable::getContent,
java.util.stream.Collectors
.toList())));
return map;
}
Why doesn’t the second version return a Map with the overridden method?
>Solution :
For simplicity’s sake let’s pretend you actually created a class that inherits from HashMap and you overrode the get method like you did. Let’s call this class MutatedHashMap.
In your first example tempMap is a MutatedHashMap, then you do your stuff in another map called map and add its elements to tempMap. Everything works fine.
In your second example you define map as a MutatedHashMap, but then you reassign another value to map with those stream operations, which of course don’t return a MutatedHashMap, but whatever collect returns. Therefore the returned object won’t have your modified get method because map is no longer a MutatedHashMap.