英文:
Why forEach(System.out::println) works but map(System.out::println) fails?
问题
我正在进行Streams教程练习(来自Oracle),并想知道为什么我会得到这个编译器错误(在Eclipse IDE中)。
无法为<R> map(Function<? super T,? extends R>)推断类型参数。
我的代码
/**
-
创建一个新列表,其中包含从原始列表转换为小写的所有字符串,并将它们打印出来。
*/
private void exercise1() {
List<String> list = Arrays.asList(
"The", "Quick", "BROWN", "Fox", "Jumped", "Over", "The", "LAZY", "DOG");list.stream().map(String::toUpperCase).map(System.out::println);
}
我还尝试过peek(System.out::println)
,但没有打印出任何内容。
我不明白为什么forEach(System.out::println)
可以正常工作,但map(System.out::println)
会失败。
英文:
I am doing the Streams tutorial exercises (from Oracle) and wondered why I am getting this compiler error (Eclipse IDE).
Cannot infer type argument(s) for <R> map(Function<? super T,? extends R>)
my code
/**
* Create a new list with all the strings from original list converted to
* lower case and print them out.
*/
private void exercise1() {
List<String> list = Arrays.asList(
"The", "Quick", "BROWN", "Fox", "Jumped", "Over", "The", "LAZY", "DOG");
list.stream().map(String::toUpperCase).map(System.out::println);
}
I also tried peek(System.out::println)
but it did not print out anything.
I don't understand why forEach(System.out::println)
works but map(System.out::println)
fails.
答案1
得分: 4
map
的目的是将每个输入的A映射到一个结果B。
System.out.println(String)返回void
,即无返回值。因此,它不适合作为map
的参数。
即使允许这样做,map
也不是一个终端操作。所有流(streams)必须以终端操作结束,否则它们将不会执行任何操作。
英文:
map
is intended to, well, map every input A to a result B.
System.out.println(String) returns void
, i. e. nothing. Thus, it is not suitable as a parameter for map
.
Even if it allowed it, map
is not a terminal operation. All streams must end with a terminal operation else they will do nothing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论