Java 8: Using Lambda

How java can be a functional language - a language that treats function as data.  Functional Interface is the approach.  Functional interface, an interface with one method that represents abstract concept: function, action, or predicate.  When referring, refer like this function rather that the function or method of object.  

If we have a Student class with integer number and our logic for comparison of two students is one with greater int value of number is greater then we can implement the Comparator interface and add this logic:

In above code, compare method belongs to Student class and in run time it will be invoked through student objects.

Another approach will be keep student class simple and when it is required to compare students the use function compare that is not a method of student class or object.

In order to build a logic in which two Student's can be compared by their number, we needed to implement the Comparator.  Such as, if we have list of students and we want to find the greatest student:
The code can be even shorter (in one line):
Student s =,s2) ->, s2.getNumber())).get();

An old school OOO programmer like me will implement like in older days:

Using normal for loop makes developer responsible for implementation and because for loop is inherently serial it is not optimized and not taking advantage of underneath – multi-core system.  With lambda code is function and iteration, filtering, and accumulation can be done in library code freeing programmer to do it explicitly.  (InfoQ, 2014, p. 11) 

InfoQ. (2014). Clarifying Lambdas in Java 8. Info Q eMag.


Popular Posts