Java Map set new value computed from Lambda expression
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.put(i, "Value " + i); }//from w w w. j a va 2 s . c o m System.out.println(map); map.forEach((id, val) -> System.out.println(val)); map.computeIfPresent(3, (num, val) -> "combined:"+val +" "+ num); System.out.println(map); System.out.println(map.get(3)); System.out.println(map.get(2)); } }
Set null to computed value
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.put(i, "Value " + i); }//from ww w .j a v a2s . c o m System.out.println(map); map.forEach((id, val) -> System.out.println(val)); map.computeIfPresent(3, (num, val) -> "combined:"+val +" "+ num); System.out.println(map); map.computeIfPresent(3, (num, val) -> null); System.out.println(map); System.out.println(map.containsKey(3)); // false } }
Set new value if absent
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.put(i, "Value " + i); }//www.j av a 2 s .c om System.out.println(map); map.forEach((id, val) -> System.out.println(val)); map.computeIfPresent(3, (num, val) -> "combined:"+val +" "+ num); System.out.println(map); map.computeIfPresent(3, (num, val) -> null); System.out.println(map); System.out.println(map.containsKey(3)); // false map.computeIfAbsent(3, num -> "new"); System.out.println(map); System.out.println(map.containsKey(3)); // true } }