Friday, February 3, 2017

Java 8 - Intro


I hope I'm not too late to the party =).... Java 8 is the most awaited and is a major feature release of Java programming language.

Java 8 is a giant step forward for the Java language. Writing this tutorial has forced me to learn a lot more about it. In Project Lambda, Java gets a new closure syntax, method-references, and default methods on interfaces. It manages to add many of the features of functional languages without losing the clarity and simplicity Java developers have come to expect.

With this short tutorial, you should have a basic understanding of the new features and be ready to start using it. (well, that's the idea)


Implementing Runnable using Lambda expression
 
One of the first thing, I did with Java 8 was  trying to replace anonymous class with lambda expressions, and what could have been best example of anonymous class then implementing Runnable interface. Look at the code of implementing runnable prior to Java 8, it's taking four lines, but with lambda expressions, it's just taking one line. What we did here? the whole anonymous class is replaced by () -> {} code block.


//Old way
new Thread(new Runnable() 
{ 
@Override public void run() 
        { 
         System.out.println("Before Java8, too much code for too little to do"); 
 } 
}).start();

  
//Java 8 way: 
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();



Event handling using Java 8 Lambda expressions
 
If you have ever done coding in Swing API, you will never forget writing event listener code. This is another classic use case of plain old Anonymous class, but no more. You can write better event listener code using lambda expressions as shown below.



// Before Java 8: 
JButton show = new JButton("Show"); 
show.addActionListener(new ActionListener() { 
 @Override public void actionPerformed(ActionEvent e) { 
  System.out.println("Event handling without lambda expression is boring"); 
 } 
}); 
  
// Java 8 way: 
show.addActionListener((e) -> { System.out.println("Light, Camera, Action !! Lambda expressions Rocks"); });



Iterating over List using Lambda expressions
 
If you are doing Java for few years, you know that most common operation with Collection classes are iterating over them and applying business logic on each elements, for example processing a list of orders, trades and events. Since Java is an imperative language, all code looping code written prior to Java 8 was sequential i.e. their is on simple way to do parallel processing of list items. If you want to do parallel filtering, you need to write your own code, which is not as easy as it looks. Introduction of lambda expression and default methods has separated what to do from how to do, which means now
Java Collection knows how to iterate, and they can now provide parallel processing of Collection elements at API level. In below example, I have shown you how to iterate over List using with and without lambda expressions, you can see that now List has a forEach() method, which can iterate through all objects and can apply whatever you ask using lambda code.



List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
  
//Old way, Prior Java 8 : 
for (String feature : features) 
{ 
 System.out.println(feature); 
} 
  
  
//In Java 8:   
features.forEach(n -> System.out.println(n)); 
 
  
// Even better use Method reference feature of Java 8 
// method reference is denoted by :: (double colon) operator 
// looks similar to score resolution operator of C++ 
features.forEach(System.out::println); 


Using Lambda expression and Functional interface Predicate

Apart from providing support for functional programming idioms at language level, Java 8 has also added a new package called java.util.function, which contains lot of classes to enable functional programming in Java. One of them is Predicate, By using java.util.function. Predicate functional interface and lambda expressions, you can provide logic to API methods to add lot of dynamic behaviour in less code. Following examples of Predicate in Java 8 shows lot of common ways to filter Collection data in Java code. Predicate interface is great for filtering.



public static void main(String[] args) {
List languages = Arrays.asList("Jamaica", "Peru", "Argentina", "France", "United States");

  
System.out.println("Countries which starts with J :");
filter(languages, (str)->((String) str).startsWith("J"));
  
  
System.out.println("Countries which ends with a "); 
filter(languages, (str)->((String) str).endsWith("a")); 
  
  
System.out.println("Print all Countries :"); 
filter(languages, (str)->true); 
  
  
System.out.println("Print no Countries : "); 
filter(languages, (str)->false); 
  
  
System.out.println("Print Countries whose length greater than 4:"); 
filter(languages, (str)->((String) str).length() > 4);
    

}
@SuppressWarnings("unchecked")
public static void filter(List names, Predicate condition) { 
 names.stream().filter((name) -> (condition.test(name))).forEach((name) -> { 
   System.out.println(name + " "); 
 }); 
}

the output for the above code is:


Countries which starts with J :
Jamaica 
-----------------------------------
Countries which ends with a 
Jamaica 
Argentina 
-----------------------------------
Print all Countries :
Jamaica 
Peru 
Argentina 
France 
United States 
-----------------------------------
Print no Countries : 
-----------------------------------
Print Countries whose length greater than 4:
Jamaica 
Argentina 
France 
United States 


If you want to see more Java 8 examples, download the complete project from my GitHub account:

https://github.com/rolando-febrero/Java8-Examples





Programming thought of the day:


  • A clean house is the sign of a broken computer.



No comments:

Post a Comment