Hello Java Streams
Streams in Java 8 are a way of creating operations to express sophisticated data processesing queries.
This example will just give a short on how to stream to very basic lists:
- Sorting an integer list.
- Filter and uppercase a string list and return it as a filtered list.
Setting up the JUnit tests
We will use two simple JUnit tests to ensure we get what we want.
In our first test, we are simply giving an
input integer list that we want and asserting that the return value equates to the
The same is true of the second test where we want to compare to string lists for our favoured result.
We'll use a
build.gradle setup to be able to run our tests:
We'll set up two methods of the class that themselves are short and functional.
The first function
sum will take our integer list, sum it up and return the sum.
The second function
filterStream will take a list of strings and also return a list of strings that will use a filter and map function chain to give us the result that we want.
sum simply turns the input list into a stream, converts the values to ints and returns the sum.
filterStream converts out input list into a stream, will filter for values that only contain "a", then uppercase those results and collect them and convert them back into a list using the
Collectors stream utility.
gradle test and if everything compiles successful you will see two ticks.
1,200+ PEOPLE ALREADY JOINED ❤️️
Get fresh posts + news direct to your inbox.
No spam. We only send you relevant content.