为什么forEach(System.out::println)能够正常工作,但是map(System.out::println)会失败?

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

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 &lt;R&gt; map(Function&lt;? super T,? extends R&gt;)

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&lt;String&gt; list = Arrays.asList(
        &quot;The&quot;, &quot;Quick&quot;, &quot;BROWN&quot;, &quot;Fox&quot;, &quot;Jumped&quot;, &quot;Over&quot;, &quot;The&quot;, &quot;LAZY&quot;, &quot;DOG&quot;);

    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.

huangapple
  • 本文由 发表于 2020年7月28日 21:03:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63134820.html
匿名

发表评论

匿名网友

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

确定