有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么将变量声明为int类型需要强制转换流?长类型不需要强制转换

为什么一个基本类型需要强制转换而另一个不需要

/* This method uses stream operations to count how many numbers in a given array
* of integers are negative
*/    

public static void countNegatives(int[] nums) {
    long howMany = stream(nums) // or: int howMany = (int) stream(nums)
            .filter(n -> n < 0)
            .count();
    System.out.print(howMany);
}

共 (2) 个答案

  1. # 1 楼答案

    count()返回long,并且不是每个long都能放入int中,因此需要一个显式强制转换来将结果存储到int。这与java-10无关。它一直存在于之前的JDK中

    如果你不想投,那么备选方案是:

    ...
    .filter(n -> n < 0)
    .map(e -> 1)
    .sum();
    

    但正如你所看到的,这并不像你的例子那样可读,因为代码本质上是说“给我一个通过过滤操作的元素的求和”,而不是“给我一个通过过滤操作的元素的计数”

    所以,如果你最终需要一个int的结果,那就去选演员吧

  2. # 2 楼答案

    Java IntStream类的count()方法已定义为返回long值。从documentation开始:

    long count() Returns the count of elements in this stream. This is a special case of a reduction and is equivalent to:

     return mapToLong(e -> 1L).sum();
    

    换句话说,Java就是这样设计的,也就是说,它与Lambda无关