Streams and LambdaExpressions in Java 8

Introduction
Typical processing patterns on collections were very hard up until Java 8 introduced a new abstraction called a Stream. Stream operations are chained together into pipelines. Other than that lambda expressions (JSR335) facilitate functional programming and simplifies the development a lot.

Workshop
For an example consider the following real world use case. Suppose we have university system where an instructor can deliver questions (multiple choice) to students. Then students start responding the question with answers. The instructor needs to find following abstract information out of all the responses.

  • Percentage of correct responses.
  • Assuming that the multiple choice question has four answer options, how many students have chosen each option.

If you implement this by following orthodox way, you may end up with many lines of code  blocks. That’s where Java8 comes to the rescue. By combining Java8 streams and lambda functions you can write each usecase in one single line of code. Suppose following Response model class get hold of all the student responses in out system.

The main method to find above abstract information can be written using java8 streams and lambda functions as follows.

Summary
In this blogpost we walked through some salient features of Java8, such as Streams and lambda expressions and realized the importance of those. I hope you enjoyed it. I’ll see you in my next blog post.

References
[3]http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html#overview

 

Comments

Popular posts from this blog

Introducing Java Reactive Extentions in to a SpringBoot Micro Service

Optimal binary search trees

Edit distance