Java 8 - my learnings in progress

Photo by qi xna on Unsplash

Java 8 - my learnings in progress

Streams, Functional Interface, Lambda Expressions etc

·

2 min read

Amazing possibilities with Streams

Though I have been coding for a while with Java, I was recently wowed by the following possibility - to think of a file as a stream of lines and operate on each line and once I executed the code with a file size of more than 100 MB, it took just a few seconds to complete the execution.

LineNumberReader br = new LineNumberReader(new BufferedReader(new InputStreamReader(classLoader.getResourceAsStream("someFile.log")))); 

List logLine = 
br 
.lines()  
.filter(a -> a.contains("error")) 
.collect(Collectors.toList()));

The expressivity of streams in Java 8 allows the developer to think fluidly. Otherwise, I generally think in terms of writing for loops to scan line by line and writing some conditions to filter out what I want and the code would have been more verbose.

Aside, from the source code above:

  • The reason I used LineNumberReader is that I wanted the lineNumber while reading.

  • Also, I noticed the difference, in whether we use parallel() construct or not. With parallel() construct, LineNumberReader was of no use, since it didn't fetch me the proper line number of each line from the file. When I ran the code, it always gave me the last line number of the log file. But, if I avoid the parallel() construct, it gave me the proper line number of the log file.

What is method reference ?

  • the method reference, :: , allows us to remove excessive code.

    • in the below code, instead of Potus::getLastName, there might have been

    • potus -> potus.getLastName()

    • but, method reference and lambda expressions are interchangeable.

  • distinct() - to remove duplicates

  • limit() - to limit the number of entries in the result.

                potuses
                .stream()
                .filter(potus -> potus.getElectionYear() < 2000)
                //.map(p -> p.getLastName()) 
                .map(Potus::getLastName)
                .distinct()
                .limit(3)
                .forEach(System.out::println);

From the above source code, there's a list of Potus objects which is treated as a stream and filtered and other operations are performed on the stream.

( thanks to a tutorial from @Marcobehler )