Non-trival Java 8 tutorial to appreciate the power of functional programming (FP)

Prerequisite: Understanding of Java 8 streams.

Q. You have a list of key value pairs (“student name”, “subject”) as shown below.

Input

The required task is to list all the subjects for each student as shown below.

Result

A. Here is the Java 8 example with lambda expressions, and then let’s discuss this in detail.

Key Points

1) The key and value objects are marked as final. One of the tenets of FP is immutability.
2) The “KeyValuePair” class is written with generics to take any data type. In this example K is of type String, and V is of type String. In fact the “main” method should be moved to a separate class of its own.
3) Note the static import of “Collectors”, which performs reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc.

Which is used for methods “groupingBy”, “mapping”, and “toList” methods. This can be rewritten with “Collectors” as shown below

Q. Why the forEach, collect, mapping, etc methods not added to java.util.List nor the java.util.Collection interface ?
A. stream( ) is a default method added to the Collection interface in Java 8. The stream( ) returns a java.util.Stream interface with multiple abstract methods like filter, map, sorted, collect, etc.

If these were added to the Collection interface and once published, it is impossible to add new methods to an interface without breaking the existing implementation. Hence, “default” methods were introduced in Java 8. From Java 8 onwards, implementation methods can now be added to interfaces providing a default implementation of the declared behavior.

Q. Why these methods were added to Stream and Collector instead of adding as a default method to the Collection class?
A. Due to backward compatibility. Many existing projects extend pre Java 8 implementation of “Collection” and should be refactored.


300+ Java Interview FAQs

Tutorials on Java & Big Data