【问题标题】:Getting the stream object in Collectors toMap method using Method References in Java 8使用 Java 8 中的方法引用在 Collectors toMap 方法中获取流对象
【发布时间】:2020-04-05 06:22:52
【问题描述】:

我正在尝试使用stream() 迭代一个列表并放入一个映射,其中键是蒸汽元素本身,值是 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 -&gt; x.toString()

【问题讨论】:

  • streamDetails.stream().collect(Collectors.toMap(Function.identity(), v-&gt;new AtomicBoolean(true)));
  • 我认为你知道语法,这只是一个错字,因为你已经在同一个调用中为 FunctionalInterface 使用了 lambda => Collectors.toMap(x -&gt; x.toString(), new AtomicBoolean(true)))

标签: java collections java-8 java-stream method-reference


【解决方案1】:

new AtomicBoolean(true) 是对Collectors.toMap 的第二个参数无效的表达式。

toMap 此处需要Function&lt;? super String, ? extends AtomicBoolean&gt;(用于将流元素(或字符串类型)转换为所需类型的映射值,AtomicBoolean),正确的参数可能是:

Collectors.toMap(x -> x.toString(), x -> new AtomicBoolean(true))

也可以用Function.identity写:

Collectors.toMap(Function.identity(), x -> new AtomicBoolean(true))

【讨论】:

  • 谢谢,它有帮助。我是 java-8 的新手,最近才开始探索它的特性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多