If you have multiple instances of the same class in a list, you will lose information if only a single object will represent a value in your map.
Instead, you have to group the objects mapped to the same key (i.e. belonging to the same class) into a collection.
With stream API, you can do it by using the built-in collector Collectors.groupingBy()
, which expects a classifier function that determines how to extract the key from the element of the stream. By default, values mapped to the same key will be grouped into a list.
Example (substitute the type Object
with your super type):
List<Object> pets2 = List.of("foo", 9, "bar", 27, new HashSet<>());
Map<String, List<Object>> classNameToPet =
pets2.stream()
.collect(Collectors.groupingBy(obj -> obj.getClass().getSimpleName()));
classNameToPet.forEach((k, v) -> System.out.println(k + " : " + v));
Output
Integer : [9, 27]
String : [foo, bar]
HashSet : [[]]
Note :
The way you are using forEach()
is not encouraged by the documentation, take a look at the code example provided in the paragraph "side-effects".
If you need to determine the actual class of your objects in order to interact with them, that means your usage of inheritance is wrong. If list pets2
has a generic parameter let's say Anymal
, then you don't have to discriminate between the subtypes of Anymal
, but take advantage from the polymorphism.