Skip to content

Latest commit

 

History

History
executable file
·
27 lines (15 loc) · 1.61 KB

d3f5.md

File metadata and controls

executable file
·
27 lines (15 loc) · 1.61 KB

Back to questions

d3f5: Streams and downcasting

In an Example class, write a method restrictToPositiveIntegers with the following signature:

  static Stream<Integer> restrictToPositiveIntegers(Stream<Number> numbers);

Given a stream of Numbers, 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!