Skip to content

Latest commit

 

History

History
executable file
·
30 lines (15 loc) · 2.32 KB

fe94.md

File metadata and controls

executable file
·
30 lines (15 loc) · 2.32 KB

Back to questions

fe94: Using Stream.map and Stream.filter

This question is about writing static methods that use the map and filter operations on streams.

  1. Create a class, Example, that we will use as a placeholder for the static methods that you will write.

  2. Write a static method with the following signature:

    static List reverseEachString(List input);

    This method should return a list whose contents are identical to the strings in input, except that each string should be reversed. For example, if you invoked reverseEachString on the list [ "hello", "world" ], you should get back the list [ "olleh", "dlrow" ].

    Your implementation should comprise a single statement that should get a stream from the list, apply multiple map operations to the stream, and collect the result back into a list.

    In particular, you should map the constructor of StringBuilder over the stream, to get a stream of StringBuilders, then map the reverse method of StringBuilder over this stream, then map the toString method of StringBuilder over the resulting stream to get a stream of Strings again.

  3. Now write an alternative version of reverseEachString, called reverseEachStringMonolithic. This should behave in a functionally identical manner to reverseEachString, but instead of applying multiple map operations, a single map operation should be used that combines the effects of all of the map operations you used in reverseEachString.

  4. Write a static method with the following signature:

    static List sqrtsOfFirstDigits(List input);

    This method should turns input into a stream, filter to just those strings that start with a digit, map each remaining string to the integer corresponding to its first digit, and then map each such integer to its square root via the Math.sqrt function, returning the resulting stream collected as a list.

  5. Now write an alternative version of sqrtsOfFirstDigits, called sqrtsOfFirstDigitsMonolithic. This should have the same behaviour as sqrtsOfFirstDigits, but should use just one call to map and one call to filter (as well as the usual calls to stream and collect).

  6. Write a main method to demonstrate that your static methods work on some example inputs.