Creating a map of child objects from parent objects

I have a list of parent objects where I want to count the appearance of child objects. I know that I can use the instanceof operator as shown below to count the occurrence of each type of object. However, I wanted to use HashMap instead of if-else branches. Am I trying to create a Map<? extends Parent, Integer> Map<? extends Parent, Integer> , but this did not work. Any suggestions?

 class Parent { // parent class } class ChildA extends Parent { // child class } class ChildB extends Parent { // child class } class ChildC extends Parent{ // child class } int countChildA = 0; int countChildB = 0; int countChildC = 0; for (Parent child : children) { if (child instanceof ChildA) { countChildA++; } else if (child instanceof ChildB) { countChildB++; } else if (child instanceOf ChildC) { countChildC++; } } // what I'm looking for Map<? extends Parent, Integer> map = new HashMap<>(); for (Parent child : children) { map.put(child, child.getValue(child)++); } 
+5
source share
1 answer

You need a Map key for Class (instance type Parent ):

 Map<Class<? extends Parent>, Integer> map = new HashMap<>(); 

And instead of:

 map.put(child, child.getValue (child)++); 

using:

 if (map.containsKey(child.getClass())) { map.put(child.getClass(), map.get (child.getClass())+1); } else { map.put(child.getClass(), 1); } 

or

 map.put(child.getClass(), map.getOrDefault(child.getClass(), 0) + 1); 
+5
source

Source: https://habr.com/ru/post/1274857/


All Articles