Chapter 13. Streams to Iterables to Sequences
Java and Kotlin both allow us to transform and reduce collections. They have different design goals and implementations, though. What does Kotlin use instead of Java streams, when should we convert, and how?
Java Streams
Java 8 introduced streams in 2014, making good use of the new lambdas. Say we want to work out the average length of some strings, except that blank strings (those with only whitespace characters) should be treated as if they are empty. Previously we might have written:
publicstaticdoubleaverageNonBlankLength(List<String>strings){varsum=0;for(vars:strings){if(!s.isBlank())sum+=s.length();}returnsum/(double)strings.size();}
With Java streams, we can express this algorithm as filter, map, and reduce by first converting the List to a Stream and applying transformations:
publicstaticdoubleaverageNonBlankLength(List<String>strings){returnstrings.stream().filter(s->!s.isBlank()).mapToInt(String::length).sum()/(double)strings.size();}
Rather than having to run the for-loop in our heads to see what this code is doing, we can see the steps of the algorithm declared line by line and rely on the runtime to implement those steps for us.
If we are really in a hurry for those results, we can even write:
publicstaticdoubleaverageNonBlankLength(List<String>strings){returnstrings.parallelStream().filter(s->!s.isBlank()).mapToInt(String::length).sum()/(double)strings ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access