【发布时间】:2018-04-17 10:46:20
【问题描述】:
这里是 Java 8。我有以下课程:
public interface Animal {
...
}
public class Dog implements Animal {
...
}
public class Cat implements Animal {
...
}
public class Elephant implements Animal {
...
}
我必须实现以下方法:
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.)
}
在我的doSomething(...) 方法中,我需要将所有映射参数合并到同一个Map<String,Animal> 映射中,但是我真的更愿意在没有我的代码的情况下这样做 必须实例化特定的地图实现(例如HashMap 等)。
意思是,我知道我可以这样做:
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...
}
如果它存在的话,我什至可以使用一些实用程序,比如Collections.merge(dogs, cats, elephants) 等。有什么想法吗?
【问题讨论】:
-
为什么要避免实例化新地图?
-
感谢@shmosel,但不是在这里寻找 XY 答案。
-
我实际上是在尝试理解需求。不是要创建一个新对象吗?不使用特定的实现?使用与参数相同的实现?支持各种实现?目前还不是很清楚你的目标是什么。请注意,到目前为止提供的所有答案实际上都实例化了一个新地图。
标签: java dictionary collections java-8