I am converting a map containing sub class values to a map of super class values using the below listed approach. Is there a better / recommended way to achieve the same?
class SuperClass{
private String name;
// getters, setters and copyOf
}
class SubClass extends SuperClass {
private String id;
// getters and setters
}
Map<String, SuperClass> superClassMap = subclass
.entrySet()
.stream()
.collect(
Collectors.toMap(Entry::getKey, entry -> SuperClass.copyOf(entry.getValue()))
);
>Solution :
If you have Guava, you can get a mapped view like this:
Maps.transformValues(SuperClass:copyOf)
Otherwise, I’d say your way is fine. Or you might prefer this:
Map<String, SuperClass> superClassMap = new HashMap<>();
subclass.forEach((k, v) -> superClassMap.put(k, SuperClass.copyOf(v)));