Ioa*_* P. 0 java java-8 java-stream
我有这门课:
\nclass Product {\n public double price;\n\n public Product(double price) {\n this.price = price;\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n还有一张地图:
\nMap<Product, Integer> products = new HashMap<>();\nRun Code Online (Sandbox Code Playgroud)\n其中包含添加的几种产品,如下所示:
\nproducts.put(new Product(2.99), 2);\nproducts.put(new Product(1.99), 4);\nRun Code Online (Sandbox Code Playgroud)\n我想使用流计算所有乘积的总和乘以值?我试过:
\ndouble total = products.entrySet().stream().mapToDouble((k, v) -> k.getKey().price * v.getValue()).sum();\nRun Code Online (Sandbox Code Playgroud)\n但它无法编译,我得到 \xe2\x80\x9c无法解析方法getValue()\xe2\x80\x9d。
我预计:
\n(2.99 * 2) + (1.99 * 4) = 5.98 + 7.96 = 13.94\nRun Code Online (Sandbox Code Playgroud)\n
条目流需要每个条目的单个参数 lambda,而不是(k,v):
double total = products.entrySet().stream().mapToDouble(e -> e.getKey().price * e.getValue()).sum();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
895 次 |
| 最近记录: |