Java 8 Map : compute()
compute()
Map compute() function computes a mapping for the specified key and its current mapped value.
It uses a BiFunction for the mapping.
Syntax :
default V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
Java8 compute() example
package com.topjavatutorial; import java.util.HashMap; import java.util.Map; public class TestMap5 { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("A", 1); map.put("B", 2); map.put("C", 3); System.out.println(map); map.compute("A", (k, v) -> (v==null ? 0 : v+1)); System.out.println(map); map.compute("D", (k, v) -> (v==null ? 0 : v+1)); System.out.println(map); } }
Output :
{A=1, B=2, C=3}
{A=2, B=2, C=3}
{A=2, B=2, C=3, D=0}
Read More
© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post