使用 Java 8 中的方法引用在 Collectors 的 toMap 方法中获取流对象。

huangapple go评论82阅读模式
英文:

Getting the stream object in Collectors toMap method using Method References in Java 8

问题

List<String> streamDetails = Arrays.asList("One", "Two");
toReplay = streamDetails.stream().collect(Collectors.toMap(x -> x, x -> new AtomicBoolean(true)));

Compile-time errors:

  1. 类型不匹配:无法从 String 转换为 K
  2. 在 Collectors 类型中,toMap(Function<? super T, ? extends K>, Function<? super T, ? extends U>) 方法对于参数 (( x) -> {}, AtomicBoolean) 不适用

我应该将我的 x -> x.toString() 替换为什么?

英文:

I am trying to iterate a list using stream() and putting in a map, where the key is the steam element itself, and the value is an AtomicBoolean, true.

List&lt;String&gt; streamDetails = Arrays.asList(&quot;One&quot;,&quot;Two&quot;);
toReplay = streamDetails.stream().collect(Collectors.toMap(x -&gt; x.toString(), new AtomicBoolean(true)));

I get the below errors at compile time.

Type mismatch: cannot convert from String to K
The method toMap(Function&lt;? super T,? extends K&gt;, Function&lt;? super T,? extends U&gt;) in the type Collectors is not applicable for the arguments ((&lt;no type&gt; x) -&gt; {}, 
	 AtomicBoolean)

What could I be doing wrong, what shall I replace my x -&gt; x.toString() with?

答案1

得分: 6

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

这里的toMap需要一个Function<? super String, ? extends AtomicBoolean>(用于将流元素(或类型String)转换为您预期的类型AtomicBoolean的映射值的函数),正确的参数可以是:

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

也可以使用Function.identity来编写:

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

new AtomicBoolean(true) is an expression that is not valid for the second parameter to Collectors.toMap.

toMap here would want a Function&lt;? super String, ? extends AtomicBoolean&gt; (intended to convert a stream element (or type String) to a map value of your intended type, AtomicBoolean), and a correct argument could be:

Collectors.toMap(x -&gt; x.toString(), x -&gt; new AtomicBoolean(true))

Which can also be written using Function.identity:

Collectors.toMap(Function.identity(), x -&gt; new AtomicBoolean(true))

huangapple
  • 本文由 发表于 2020年4月5日 14:22:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/61038794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定