Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting a Map of subclass values to map of SuperClass values

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading