英文:
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:
- 类型不匹配:无法从 String 转换为 K
- 在 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<String> streamDetails = Arrays.asList("One","Two");
toReplay = streamDetails.stream().collect(Collectors.toMap(x -> 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<? super T,? extends K>, Function<? super T,? extends U>) in the type Collectors is not applicable for the arguments ((<no type> x) -> {},
AtomicBoolean)
What could I be doing wrong, what shall I replace my x -> 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<? super String, ? extends AtomicBoolean>
(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 -> x.toString(), x -> new AtomicBoolean(true))
Which can also be written using Function.identity
:
Collectors.toMap(Function.identity(), x -> new AtomicBoolean(true))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论