Lambda Expression Basic Example – Java 8

Lambda Expression Basic Example – Java 8

Why Java 8 supports functional programming is a big debate we can avoid for now. Lets try to understand what the features Java 8 has given for supporting functional programming. First thing we hear is Java 8 has provided Lambda Expressions, According to Oracle’s Chief Architect Mark Reinhold, The Single Largest Upgrade Ever. Lets start learning the Lambda expression now.

Lambda’s are anonymous functions which doesn’t need a name, input arguments or return type. If I say like that you might think why and how they are useful ?

Shall we really use them? If you could see a very small and basic example given for Prime Numbers, you would be able to understand the simplicity and ease of use of Lambda’s. Explanation of the code is given below the example.

Note: Please look at the methods [ isPrimeNum(Old School of Coding) and isPrime( New School of Functional Coding)].

package com.ravi.lambda;

import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.IntStream;

public class PrimeNumber {

     public static void main(String[] args) {

          // Old Style
          System.out.println(" 1 is Prime ? -" + isPrimeNum(1));
          System.out.println(" 2 is Prime ? -" + isPrimeNum(2));
          System.out.println(" 3 is Prime ? -" + isPrimeNum(3));
          System.out.println(" 4 is Prime ? -" + isPrimeNum(4));

          // New Style
          System.out.println(" 1 is Prime ? -" + isPrime(1));
          System.out.println(" 2 is Prime ? -" + isPrime(2));
          System.out.println(" 3 is Prime ? -" + isPrime(3));
          System.out.println(" 4 is Prime ? -" + isPrime(4));

     }
     /**
     *
     * @param number
     * @return
     */
     static boolean isPrimeNum(Integer number){
          if(number == 1 ){
              return false;
          }
          for(int i=2; i< number; i++){
               if(number % i == 0 ) {
                    return false;
               }
          }
     return true;
     }

     /**
     *
     * @param number
     * @return
     */
     static boolean isPrime(int number){
     // Functional or Declarative Way of doing
     return number > 1 && IntStream.range(2, number).noneMatch( index -> number % index == 0 );
     }
}

Lets look at the isPrimeNum method. Did you notice anything strange ? I guess no, because we know that Java works that way.

Loop over all numbers which are greater than 2 till n-1, as 1 is not a prime number and any number can be divisible by 1, we would like to start with 2. So, we had to handle the case of 1 separately.

Instead of Looping the code we could do it with Functional way –  isPrime demonstrates that code.

The easiest way to identify a Lambda Expression is “->“. A Lambda can take Optional Parameters, and executes the expressions or statements with in the braces.  Let me explain the above example.

First condition we are checking is number greater than 1 and Stream is the new API given by Java 8 [Which can be used in place of Collections… Read More ] which provides sequence of events. I have used “IntStream” which is defined for Integers, which has this Static Method called Range (Runs the loop from 2 till the given number )and noneMatch (returns a Boolean value, whether no elements of this stream match the provided predicate )instance method which take Predicate as input, this is where we have used a Lambda expression to see the number is divisible by the index.

Lambda’s has too many things, I hope this is a very good starting point for you. I would try to give you how to make it generic and re use a Lambda expression in next blog.

References:

Oracle Blog about Lambda Expressions

Lambda Expression FAQ

Advertisements
Build Your Own Technology Radar

Build Your Own Technology Radar

I am impressed by ThoughtWorks Technology Radar, The technical team of Thoughtworks meet every year for a week and discuss about this Radar and document all the positives and negatives of the Technology/Framework/Tool/Technique. They have divided each category into four sections namely “ASSESS”, “TRIAL”, “ADOPT” or “HOLD”.  I thought of preparing my own Radar after getting the inspiration, I might not able to suggest you to ADOPT / HOLD technologies or frameworks, As developers we should have to try some new stuff. All developers should have tried at least  5 technologies / frameworks / tools in a year. As most of my experience is in Java/ J2EE technologies, I am more focused on Java related technologies.

Below are the things I would like to suggest this year 2014, Let’s start with simpler things 🙂

Play with JDK 8

I hope all of you are already using JDK 7, there might be some legacy applications running on JDK6 and below, but this should be your first thing to explore the new features of JDK8 and how to leverage these features in your current application. You should be able to submit a report to your Lead/Architect/Manager, the advantages you are going to get. It looks pretty easy but it might take little more time than you expect and there could be dependencies/incompatibilities like Servers Jboss/ Web logic etc. which might depend on your server JDK. Flash news, there is initial version of JDK9 out for download.

Try atleast One Alternate JVM language

There are lot of alternative JVM languages available in the market, most of them are focused on functional not object oriented. This would be a very good opportunity for you come out of Object oriented thinking and think in functional programming way. Sometimes this would help a lot. So, I would suggest you to try out Scala or Closure if you are interested in functional programming, try Groovy if all you need is a scripting language. There are two more flavors available named JRuby and Jython for Ruby and Python fans. Based on your interest level you should try any one of these.

Java Script { no more only client side code }

Even though it started it’s journey as client side validation script, It made it a long way until it reached a server side script like Node JS. Even today it is the most efficient client side DOM manipulator from plain java script, jQuery, Angular JS and Ember JS and KnockOut and what NOT. Java Script made its way from direct call back functions to defining MV* patterns in the client side.Along with making its position strong in client side, java script moved to Server side too, this is a significant event in the Java script life. Node JS is the trend setter for server side java script frameworks, there are already tons of frameworks available for Node JS ( like expressjs, compoundjs, etc.). There are tools like Grunt (Ant like Build tool for JS), Yo (the scaffolding tool) and Bower (for package management).

I suggest everybody to try out at least one small test application using Node JS in 2014.

IMDBs (In Memory DB)

This is a new trend in software industry and there are lot of use cases where you need In memory DBs for Performance, standard Analytics, and even now the real time analysis of data. The idea behind these data bases is to store the data directly in memory( RAM) instead of writing them into file system. This would reduce the indexing and other overloads when you want to retrieve the data hence you get more performance. The support for ACID properties for these databases is in debate till date, but there are new generation databases like VoltDB which support ACID properties as well. This VoltDB has a very good support for Spring as well.

I would suggest you to try out at least one IMDB from the list

IoT(Internet of Things)

This is something all developers should try, because the world is moving towards this, as we all now have smart TVs, smart Fridges and of-course smart mobiles. All these devices should be connected and the communication should happen between these devices and the server. ” You should be able to switch on your A.C half an hour before you reach home, You want a cool home before you reach, are’t you? “.

There are too many options to try out Java IoT programming. There is a community dedicated to IoT from Java.net. Recently Java launched a MOOC(Massive Open Online Course) for Java Embedded too. This is the reason you should try it out.

Note: you might have to spend some dollars to buy the boards like Raspberry Pi or Intel Galileo or Edison.

Hope this article might have given you some idea on some of the technologies / frameworks / DBs etc you could try out this year. All your inputs to make my list better are appreciated.

Happy Reading and Coding 🙂

How to train a software Engineer?

How to train a software Engineer?

How we get software engineers in current world, most of the software engineers in India are not studied the software as a mainstream subject in their curriculum [ For Eg. Electronics, Electrical, Mechanical and even Civil ]. Perhaps there is a small % of people who might have studied software / IT as a main stream.

When we hire non IT/Software graduates as software engineers, do we really provide the necessary training to them ? Even the people who are studying the Software main stream is the course content relevant to the current industry ?  I was trying to find out how many times the syllabus changes for software / IT engineers, typically it is 6-7 years for Indian universities. I am not sure about the other countries like US. Even after change there are very less changes happened.

Methodology Learning:

There is a subject called “Software Engineering”, When I studied 10 years back it talked about the SDLC(System Development Life Cycle) Water fall model development with Plan, Analyse, Design, Implement and Maintain. This might sound very familiar to us, still I didn’t use this methodology for more than 5 years now, as Agile Methodology is the latest and which is working well for the real time projects. I am sure still our students are not aware of this in college, they still learn the water fall model come out of college.

No company can give them a proper training on the Scrum/Kanban or Agile methodology when they are going to join. This is a learning he/she has to do along with the project. There are many things we learn on the job. This would really help the companies / project teams to make the new joiner up to the mark or pace.

Technical Learning:

I observed in some advance universities, they have added Java, .Net, PHP languages as a subject to learn for the students of Engineering. Now the question for me is, Does this help to the software industry ? I am still skeptical about it. In these subjects they are focusing on the syntax and practical examples of syntax etc. Where as I would prefer the knowledge of the student should be focused on Object Oriented thinking.

I usually give the freshers a program called “Railway Reservation”. It has some specifications, At a time you can book 5 seats and the seats should be near by if they are available. There are only 70 seats in each compartment etc.  Most of the people would not ask any questions after reading the requirements. They assume lot of things. Then they start writing code, taking a two dimensional array. They don’t even bother about thinking what are the objects involved in this and how they would behave? What are the attributes they possess ? All this could be because of our education system. From the day we start programming we tell students, how to write program [Find Prime number/not, Print Fibonacci series, etc. ]. So we start writing programs from beginning. Perhaps we should teach the students, Designing. How to analyse the given problem, does it follow any pattern, what is the desired behavior of the problem, how can we optimize the code already done.

To come up with these kind of questions the students should know what are the Design Principles, what are the Design patterns already available to solve their current problem. This kind of practical syllabus would be more relevant for the students as well as employer who hire these students.

At least the basics of Design principles and Design Patterns are a must to have things in any computer science course. Hope you all agree with me. Thanks for taking your time and reading my ideas.