1.4-Software-Development-Principles

Java Stream exercises

You will need to create your own project for this exercise and copy some code to its folder.

All exercises can become separate (static) methods in one class for your convenience.

Note: This exercise is intended to be done using the Java Streams API. You can solve these problems differently, but that is not really the point!

Exercise 1 Normal for-loop

Count the number of letters for all strings starting with a “t” using a ‘normal’ for loop

Exercise 2 Steam – map reduce

Count the number of letters for all strings starting with a “t” using a stream (map followed by reduce).

Do not use the method operator (::)

Exercise 3 Method operator

Count the number of letters for all strings starting with a “t” using a stream (map followed by reduce). Use the method operator (::) for the map and reduce.

Hint: Look at the sum() method implemented in the Integer class.

Exercise 4 Count

Count all words with an even number of letters.

Exercise 5 Average

What is the average number of letters used in the words?

Hint: use .mapToInt() combined with average() or .collect combined with Collectors.averagingInt ().

Exercise 6: Counting letters

Create a method int countLetters(String input) that for any input (String) returns the number of letters.

So hello should return the value 5.

hint have a look at the api of the String class for any methods returning a stream

Exercise 7: Filtering words based on a letter

Create a method String[] getWordsStartingWith(char letter, String input) that for any input (String) returns all words in that line (separated by white spaces) that start with that letter.

So this is a test, filtered by the letter t should return a String array containing ` [“this”, “test”]`.

Exercise 8: Calculate the average amount of letters for each word

Create a method double calculateAverageWordLenght(String input) that calculates the average number of letters for all words inside a given sentence.

So this is a long test results in 3.0 and this is a test in 2.75.

Exercise 9: Combine exercise 6 and 7 - Count the letters from filtered words.

Create a method int[] countWordsStartingWith(char letter, String input) that filters a sentence, as described by exercise 7 and then counts the letters of all filtered as described in exercise 6.

So this is a test, filtered by the letter t should return an integer array containing [4, 4].

Exercise 10: Write unittests for these assignments

We have provided a unittest in the tests folder. Rewrite the assignments so that the methods return a value, these methods may even be defined as static.

Test all assignments with different input, the example, but also other lists or values.