简体   繁体   中英

Why does declaring a variable as type int require casting a stream? long type does not require a cast

Why does one primitive type require casting and and the other does not?

/* 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);
}

The count() method of the Java IntStream class has been defined to return a long value. From the 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();

In other words, this is how the Java is designed, ie it has nothing todo with Lambda.

count() returns long and not every long can fit into an int hence an explicit cast is required to store the result into an int . This is nothing to do with java-10. it's always been there in previous JDK's.

If you don't want to cast then the alternative would be:

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

but as one can see this is not as readable as your example because the code essentially says "give me a summation of the elements that pass the filter operation" instead of "give me a count of the elements that pass the filter operation".

So, ultimately if you need the result as an int then go for the cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM