【发布时间】:2020-07-28 13:03:54
【问题描述】:
我正在做 Streams 教程练习(来自 Oracle)并想知道为什么我会收到此编译器错误(Eclipse IDE)。
Cannot infer type argument(s) for <R> map(Function<? super T,? extends R>)
我的代码
/**
* 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);
}
我也试过peek(System.out::println),但它没有打印出任何东西。
我不明白为什么 forEach(System.out::println) 有效但 map(System.out::println) 失败。
【问题讨论】:
-
因为
map想要一个返回值的函数,而forEach不需要。 -
使用 map 的正确方法是收集输出并打印出来。
List<String> collect = list.stream().map(String::toUpperCase).collect(Collectors.toList()); -
我也试过
peek(System.out::println),但它没有打印出任何东西。 -
那是因为
peek是一个非终端操作,在终端操作从流中提取数据之前,它不会做任何事情。
标签: java java-8 java-stream