Home  >  Core Java

Java ConcurrentHashMap: reduce() Example

By Arvind Rai, February 13, 2022
On this page we will learn reduce() method of Java ConcurrentHashMap class.
Find the Java doc of reduce() method.
<U> U reduce(long parallelismThreshold,
   BiFunction<? super K,? super V,? extends U> transformer,
   BiFunction<? super U,? super U,? extends U> reducer) 
Parameters :

1. parallelismThreshold - The number of elements needed for this operation to be executed in parallel.

2. transformer - A BiFunction that transforms the element. It means the BiFunction has key/value as input and combine it into one output.

3. reducer - A BiFunction that accumulates all the outputs of transformer function.

Returns : The result of accumulating the given transformation of all key/value pairs.

The reduce method returns the result of accumulating the given transformation of all key/value pairs using the given reducer to combine values, or null if none.

Example-1

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);
  }
} 
Output
Mohan-20, Sohan-22, Vishal-25 

Example-2

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
  }
} 

Reference

Java ConcurrentHashMap
POSTED BY
ARVIND RAI
ARVIND RAI











©2022 concretepage.com | Privacy Policy | Contact Us