【发布时间】:2015-03-10 18:06:18
【问题描述】:
这是我的代码:
// assuming HashMap<String, Integer> hashmap
double sum = hashmap.values().stream()
.reduce(.0, (i, v) -> i + Math.pow(v,2) + 0.5 );
在这种情况下,reduce 应该采用 (Integer i) 和 (double v) 并将它们相加,然后将此 reduce 作为双精度数返回。
相反,我得到了这个错误:
- The method reduce(Integer, BinaryOperator<Integer>) in the type Stream<Integer> is not applicable for the arguments (double, (<no type> i, <no type> v) -> {})
- Type mismatch: cannot convert from double to Integer
减少,
但是,这修复了:
// assuming HashMap<String, Integer> hashmap
double sum = hashmap.values().stream()
.map((t)->(double)t)
.reduce(.0, (i, v) -> i + Math.pow(v,2) + 0.5 );
有没有更优雅的方法?
【问题讨论】:
-
就您期望发生的事情而言,我不清楚您实际上要实施什么操作。你能用普通的 for-each 编写一个实现来更清楚吗?
标签: java java-8 java-stream