【发布时间】:2021-09-13 16:14:17
【问题描述】:
这里是 Java 8。我有一个字符串数组:
String[] animals = getsomehow(); // "dogs", "cats", "sheep", etc.
然后我有一个映射,其中键是字符串(具体而言,与上面数组中的动物的 some 相同的文字值),并且值是计数(代表那些动物):
Map<String,Integer> animalCounts = new HashMap<String,Integer>();
animalCounts.put("sheep", 4);
animalCounts.put("dogs", 2);
animalCounts.put("cats", 0);
animalCounts.put("porcupines", null);
animalCounts.put("dolphins", 43);
我试图弄清楚如何使用 Stream API 来遍历我的 animals 数组,并得出动物的总数。例如,如果我的 animals 数组中包含“绵羊”和“海豚”,那么动物的总数将为 4 + 43 = 47。
到目前为止我最好的尝试:
int totalAnimals = Arrays.stream(animals)
.reduce(
0,
(subtotal, animal) -> subtotal + animalCounts.get(animal));
但是,这会导致 0 的标识值出现编译器错误:
"必需类型:字符串"
谁能看出我哪里出错了?
【问题讨论】:
-
你为什么要这么做
animalCounts.put("porcupines", null);?null与0有何不同,为什么密钥porcupines仍需要同时成为Map的一部分? -
澄清:“狗”可以两次成为
animals数组的一部分吗?如果是的话,你会把狗的数量加起来两次吗? -
感谢 Naman,我个人会在地图上使用
put("porcupines", null),但这是我的情况:地图条目存在非空键但null值。关于animals数组中的重复项的要点。由于我的应用程序保证不会发生这种情况,我会说重复计算它们是安全的。
标签: java collections java-stream reduce