Java流问题,mapToInt和average方法。

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

Java stream question, mapToInt and average method

问题

为什么我可以在一个上调用 average() 方法,但在另一个上却不能?它们不应该是等效的吗?

示例1 - 能够运行

List<String> stringList = new ArrayList<>();
    stringList.add("2");
    stringList.add("4");
    stringList.add("6");
// 字符串数组 ("2", "4", "6")
averageValue = stringList.stream()
                .mapToInt(s -> Integer.valueOf(s))
                .average()
                .getAsDouble();   

示例2 - 无法编译(删除了 mapToInt 调用,因为已经传递了 Integer 流)

List<Integer> IntegerList = new ArrayList<>();
        IntegerList.add(2);
        IntegerList.add(4);
        IntegerList.add(6);
 
averageValue = IntegerList.stream()
                    .average()
                    .getAsDouble();  

问题是,既然我已经传递了整数流,为什么我需要调用 mapToInt 方法呢?

英文:

Why can I call average() method on one but not on the other? Shouldn't they be equivalent?

example 1 - works

List&lt;String&gt; stringList = new ArrayList&lt;&gt;();
    stringList.add(&quot;2&quot;);
    stringList.add(&quot;4&quot;);
    stringList.add(&quot;6&quot;);
// String array (&quot;2&quot;,&quot;4&quot;, &quot;6&quot;
averageValue = stringList.stream()
                .mapToInt(s -&gt; Integer.valueOf(s))
                .average()
                .getAsDouble();   

example 2 - doesn't compile (deleted mapToInt call because already passing Integer stream)

List&lt;Integer&gt; IntegerList = new ArrayList&lt;&gt;();
        IntegerList.add(2);
        IntegerList.add(4);
        IntegerList.add(6);
 
averageValue = IntegerList.stream()
                    .average()
                    .getAsDouble();  

Question, is why do I need to call mapToInt method when Im already passing it a stream of Integers?

答案1

得分: 9

有两种不同的类型:一个 Stream<Integer> 和一个 IntStream

Java 的泛型不能只适用于某些泛型上的方法。例如,它不能只有 Stream<Integer>.average() 而不同时也有 Stream<PersonName>.average(),尽管人名的平均值没有意义。

因此,Stream 有一个 mapToInt 方法,将其转换为 IntStream,然后提供了 average() 方法。

英文:

There are two different types: a Stream&lt;Integer&gt; and an IntStream.

Java's generics can't have methods that only apply on some generics. For example, it couldn't have Stream&lt;Integer&gt;.average() and not also have Stream&lt;PersonName&gt;.average(), even though the average person name doesn't make sense.

Therefore, Stream has a mapToInt method that converts it into an IntStream, which then provides the average() method.

答案2

得分: 4

IntStream提供了average()方法,因此要使用它,您需要通过使用mapToInt方法将Stream&lt;Integer&gt;转换为IntStream

英文:

IntStream provides average() method, so to use it you need to convert Stream&lt;Integer&gt; to IntStream by using mapToInt method.

huangapple
  • 本文由 发表于 2020年4月6日 01:15:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/61046441.html
匿名

发表评论

匿名网友

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

确定