[英]Java Stream API : what kind of map method collect(Collectors.toMap()) returns?
[英]Getting the stream object in Collectors toMap method using Method References in Java 8
我正在尝试使用stream()
迭代列表并放入 map,其中键是蒸汽元素本身,值是 AtomicBoolean,true。
List<String> streamDetails = Arrays.asList("One","Two");
toReplay = streamDetails.stream().collect(Collectors.toMap(x -> x.toString(), new AtomicBoolean(true)));
我在编译时收到以下错误。
Type mismatch: cannot convert from String to K
The method toMap(Function<? super T,? extends K>, Function<? super T,? extends U>) in the type Collectors is not applicable for the arguments ((<no type> x) -> {},
AtomicBoolean)
我可能做错了什么,我应该用什么替换我的x -> x.toString()
?
new AtomicBoolean(true)
是对Collectors.toMap
的第二个参数无效的表达式。
toMap
这里需要一个Function<? super String, ? extends AtomicBoolean>
Function<? super String, ? extends AtomicBoolean>
Function<? super String, ? extends AtomicBoolean>
(旨在将 stream 元素(或字符串类型)转换为您想要的类型 AtomicBoolean 的 map 值),并且正确的参数可以是:
Collectors.toMap(x -> x.toString(), x -> new AtomicBoolean(true))
也可以使用Function.identity
编写:
Collectors.toMap(Function.identity(), x -> new AtomicBoolean(true))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.