仅仅使用Java 8中的新lambda和功能特性,我不确定如何做到这一点。
例如,以下内容有效:
Map<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put("C", 3); map.compute("A", (k, v) -> v == null ? 42 : v + 41));
但是以下内容给我语法错误:
BiFunction x = (k, v) -> v == null ? 42 : v + 41; map.compute("A", x);
有任何想法吗?
您已经忘记了BiFunction:
BiFunction
public static void main(final String[] args) throws Exception { final Map<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put("C", 3); final BiFunction<String, Integer, Integer> remapper = (k, v) -> v == null ? 42 : v + 41; map.compute("A", remapper); }
运行:
PS C:\Users\Boris> java -version java version "1.8.0-ea" Java(TM) SE Runtime Environment (build 1.8.0-ea-b120) Java HotSpot(TM) 64-Bit Server VM (build 25.0-b62, mixed mode)