sme*_*eeb 3 java collections dictionary java-8
Java 8在这里。我有以下课程:
public interface Animal {
...
}
public class Dog implements Animal {
...
}
public class Cat implements Animal {
...
}
public class Elephant implements Animal {
...
}
Run Code Online (Sandbox Code Playgroud)
我必须实现以下方法:
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.)
}
Run Code Online (Sandbox Code Playgroud)
在我的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...
}
Run Code Online (Sandbox Code Playgroud)
如果有某个实用程序,我什至可以使用它,例如Collections.merge(dogs, cats, elephants)
,等等。有什么想法吗?
一种实现方法是创建一组条目流,然后对其进行平面映射以包含条目流,然后将其收集到地图中。
Map<String,Animal> animals =
Stream.of(dogs.entrySet(), cats.entrySet(), elephants.entrySet())
.flatMap(Set::stream)
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
//Stream.of(dogs, cats, elephants).flatMap(m -> m.entrySet().stream()) could also be an option
Run Code Online (Sandbox Code Playgroud)
也不是单线的并且没有使用Map#putAll
以下内容的流:
Map<String,Animal> animals = new HashMap<>(dogs);
animals.putAll(cats);
animals.putAll(elephants);
Run Code Online (Sandbox Code Playgroud)