Java Reference
In-Depth Information
You'll learn in the next section that boxed is particularly useful when you deal with numeric
ranges that need to be boxed into a general stream.
Default values: OptionalInt
The sum example was convenient because it has a default value: 0. But if you want to calculate
the maximum element in an IntStream, you need something different because 0 is a wrong
result. How can you differentiate that the stream has no element and that the real maximum is 0?
Earlier we introduced the Optional class, which is a container that indicates the presence or
absence of a value. Optional can be parameterized with reference types such as Integer, String,
and so on. There's a primitive specialized version of Optional as well for the three primitive
stream specializations: OptionalInt, OptionalDouble, and OptionalLong.
For example, you can find the maximal element of an IntStream by calling the max method,
which returns an OptionalInt:
OptionalInt maxCalories = menu.stream()
.mapToInt(Dish::getCalories)
.max();
You can now process the OptionalInt explicitly to define a default value if there's no maximum:
5.6.2. Numeric ranges
A common use case when dealing with numbers is working with ranges of numeric values. For
example, suppose you'd like to generate all numbers between 1 and 100. Java 8 introduces two
static methods available on IntStream and LongStream to help generate such ranges: range and
rangeClosed. Both methods take the starting value of the range as the first parameter and the
end value of the range as the second parameter. But range is exclusive, whereas rangeClosed is
inclusive. Let's look at an example:
 
Search WWH ::




Custom Search