Java 8 here. I have the following classes:
public interface Animal {
...
}
public class Dog implements Animal {
...
}
public class Cat implements Animal {
...
}
public class Elephant implements Animal {
...
}
I have to implement the following method:
void doSomething(Map<String,Dog> dogs, Map<String,Cat> cats, Map<String,Elephant> elephants) {
// TODO:
// * Merge all dogs, cats & elephants together into the same Map<String,Animal>,
// but...
// * Do so generically (without having to create, say, a HashMap instance, etc.)
}
In my doSomething(...) method, I need to merge all the map arguments into the same Map<String,Animal> map, but I'd really prefer to do so without my code having to instantiate a specific map implementation (such as HashMap, etc.).
Meaning, I know I could do this:
void doSomething(Map<String,Dog> dogs, Map<String,Cat> cats, Map<String,Elephant> elephants) {
Map<String,Animal> animals = new HashMap<>();
for(String dog : dogs.keySet()) {
animals.put(dog, dogs.get(dog));
}
for(String cat : cats.keySet()) {
animals.put(cat, cats.get(cat));
}
for(String elephant : elephants.keySet()) {
animals.put(elephant, elephants.get(elephant));
}
// Now animals has all the argument maps merged into it, but is specifically
// a HashMap...
}
I'm even fine using some utility if it exists, like maybe a Collections.merge(dogs, cats, elephants), etc. Any ideas?