在本文中,我们将学习 Java ConcurrentHashMap
类的 reduce()
方法。
找到 reduce()
方法的 Java 文档。
<U> U reduce(long parallelismThreshold,
BiFunction<? super K,? super V,? extends U> transformer,
BiFunction<? super U,? super U,? extends U> reducer)
参数 :
1。 parallelismThreshold - 并行执行此操作所需的元素数。
2。 transformer - 转换元素的 BiFunction
。 这意味着 BiFunction
将键/值作为输入并将其组合成一个输出。
3。 reducer - 一个 BiFunction
,它累积了 transformer 函数的所有输出。
Returns :所有键/值对的给定转换累加的结果。
reduce
方法返回使用给定 reducer 组合值的所有键/值对的给定转换累积的结果,如果没有,则返回 null。
ReduceDemo1.java
package com.concretepage;
import java.util.concurrent.ConcurrentHashMap;
public class ReduceDemo1 {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("Mohan", 20);
map.put("Sohan", 22);
map.put("Vishal", 25);
String output = map.reduce(1, (k, v) -> k + "-" + v,
(s1, s2) -> s1 + ", " + s2);
System.out.println(output);
}
}
输出
Mohan-20, Sohan-22, Vishal-25
ReduceDemo2.java
package com.concretepage;
import java.util.concurrent.ConcurrentHashMap;
public class ReduceDemo2 {
public static void main(String[] args) {
ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>();
map.put(2, 20);
map.put(3, 30);
map.put(4, 40);
Integer output = map.reduce(1, (k, v) -> k * v,
(i1, i2) -> i1 + i2);
// 2*20 + 3*30 + 4*40
System.out.println(output); // Output: 290
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.concretepage.com/java/java-concurrenthashmap-reduce
内容来源于网络,如有侵权,请联系作者删除!