In an Example
class, write a method restrictToPositiveIntegers
with the following signature:
static Stream<Integer> restrictToPositiveIntegers(Stream<Number> numbers);
Given a stream of Number
s, the method should return the substream of this stream comprised of only those numbers of type Integer
whose integer value is positive.
The body of restrictToPositiveIntegers
should be a single statement, and it should not convert the input stream to a list or any other collection.
Write a main
method showing that if you create a List<Number>
called numbers
populated with various Integer
, Float
, Double
and Short
values, and then do:
System.out.println("Positive integers from " + numbers + " are: "
+ restrictToPositiveIntegers(numbers.stream()).collect(Collectors.toList()));
you see precisely the positive integers from your list of numbers being output.
Try creating a List<Float>
or List<Integer>
and invoking restrictToPositiveIntegers
on a stream derived from each of these lists. You should find that this does not compile.
Advanced: Write a method, restrictToPositiveIntegersBoundedWildcard
, that can take a stream of any type T
that is Number
or one of Number
's subclasses and return the substream containing only those positive integers from the original stream.
Hints
- You will need to use instance testing and downcasting in the implementation of
restrictToPositiveIntegers
. - For
restrictToPositiveIntegersBoundedWildcard
, the clue is in the name!