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!
Count the number of letters for all strings starting with a “t” using a ‘normal’ for loop
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 (::)
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.
Count all words with an even number of letters.
What is the average number of letters used in the words?
Hint: use .mapToInt() combined with average() or .collect combined with Collectors.averagingInt ().
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
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”]`.
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
.
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]
.
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.