我有一个 Map
和 List
看起来像
int total = 0;
int incr = 10;
Map<String, Boolean> hashMap = new HashMap();
hashMap.put("A", true);
hashMap.put("B", false);
hashMap.put("C", true);
List<String> states = new ArrayList<>();
states.add("A");
states.add("B");
states.add("D");
states.add("E");
states.add("F");
每次我从 Map
的列表中找到一个键,然后我想通过增加值来增加我的总数;
states.stream()
.filter(s -> hashMap.containsKey(s) && hashMap.get(s))
.forEach((s) -> {total = total + incr;} );
最佳答案
您的变量 total
必须是最终的(即:带有关键字 final)或实际上是最终的(即:您只在 lambda 之外为其赋值一次)。否则,您不能在 lambda 表达式中使用该变量。你可以像这样修复它,
int total = states.stream()
.filter(s -> hashMap.containsKey(s) && hashMap.get(s))
.mapToInt(k -> incr).sum();
如以下评论所述,这可以进一步简化为,
int total = states.stream()
.filter(s -> hashMap.getOrDefault(s, false))
.mapToInt(k -> incr).sum();
关于java - 如何在 Java 8 流中增加计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53166265/