是否有一种优雅的方式将其转换Map<P, Optional<Q>>为稀疏Map<P, Q>?
这应该工作,但它有点meh:
Map<P,Optional<Q>> map = ...;
Map<P,Q> map2 = map.entrySet()
.stream().filter(e -> e.getValue().isPresent())
.collect(Collectors.toMap(e -> e.getKey(), e->e.getValue().get()));
Run Code Online (Sandbox Code Playgroud) List<String> strings = Arrays.asList("3","55","3");
Map<String,Integer> map = strings
.stream()
.collect(Collectors.toMap(s ->s, s -> s.length()));
Run Code Online (Sandbox Code Playgroud)
回报
java.lang.IllegalStateException: Duplicate key 1
Run Code Online (Sandbox Code Playgroud)
我希望在哪里复制密钥3