Home > Enterprise >  Converting a Map of subclass values to map of SuperClass values
Converting a Map of subclass values to map of SuperClass values

Time:10-31

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()))
  );

EDIT:

Below is the reverse operation that I am performing -

superClassMap
      .entrySet()
      .stream()
      .collect(
        Collectors.toMap(
          Entry::getKey,
          entry ->
            SubClass
              .builder()
              .setName(entry.getValue().getName())
              .setId(anotherMap.get(entry.getKey()).getId())
              .build()
        )
      );

CodePudding user response:

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)));

CodePudding user response:

To modify all the values of the map, you can use Java 8 method Map.replaceAll(), which expects a BiFunction generating a new value based on the previous value and a key:

Map<String, SuperClass> superClass = new HashMap<>(subclass);

superClass.replaceAll((k, v) -> SuperClass.copyOf(v));

Note: HashMap's copy-constructor expects an argument of type Map<? extends K, ? extends V>, therefore we can provide a Map having values of subtype without issues owing to upper-bounded wild card.

  • Related