Stream examples Part 3 - Conclusion

I would like to wrap up with some snippets I use a lot! Collect to a map When you want to collect to a Map, you need a function for the key and a function for the value. Suppose you have a list of Person objects with a firstname and last name. If you want to map the firstname to the lastname, you would write something like this: Map<String, String> firstToLastMap = persons....

April 8, 2019 · 2 min

Stream examples Part 2 - Reducers

Next to collectors, Streams offer reducers as well. You can consider it as building a result, starting from a partial solution and building on top of that. It is actually comparable to how the result is built up when using recursion. As an example, let’s take the sum of all integers starting from 1 up until n. The trivial solution is 0 for the ‘empty case’, this is the value before you start looping....

April 1, 2019 · 2 min

Stream examples Part 1 - Collectors

Streams are quite fun - in short: it’s a different approach to writing loops. Suppose you have a List of Strings and you want to filter out the String starting with an ’s' and put them in a new List. List<String> sStrings = new ArrayList<>(); for(int i = 0; i < strings.size(); i++){ if(strings.get(i).startsWith('s')){ //do something with strings starting with s sStrings.add(strings.get(i)); } } Although still readable, there is a lot of redundant code: the for loop itself with the counter and condition, the if statement....

March 31, 2019 · 2 min