Code Pumpkin

Java8 Features

April 22, 2017
Posted by Pumpkin
Subscribe

Java 8 is released in March 2014. In this article, we will look into some of the java 8 features with examples.

You can download JDK 1.8 from here based on your OS Platform requirements.

We are going to cover below important features of the Java8:


Lambda Expressions:

In Java8, Lambda expression has been introduced as a part of Java's support for functional programming. In simple word, Lambda expression means an anonymous function which will not belong to any class or entity.

By using lambda expression, we can increase the code readability by doing declarative coding and code maintainability as well. Below is syntax and example of Lambda expression.


(Comma separated Arguments) -> expression body

Example of lambda Expression:


 Thread th = new Thread(() -> System.out.println("Running in new thread created by Lambda"));

If you want to explore the lambda expressions in more details you can always refer to the article Lambda Expression | Java8.


Functional Interface:

Java developer around the world frequently uses the Runnable, Comparator, Callable etc. One common thing about the above mentioned interfaces is they have only one method declared to be implemented. These interfaces are called Single Abstract Method(SAM). It is normally implemented using anonymous class. In Java8 this concept recreated as functional interface and now these interfaces can be implemented using Lambda expressions as below:



public class Sample {

	public static void main(String[] args){
		
		Thread th= new Thread(() -> System.out.println("Running in new thread"));
		th.start();
	}
}

There’s an annotation introduced- @FunctionalInterface which can be used for compiler level errors when the interface you have annotated is not a valid Functional Interface. The detailed discussion for the functional interface covered in article Functional Interface | Java8.


Stream Collection Type:

Stream classes were introduced in java.util.stream package to support  functional-style operations on streams of elements, such as map-reduce transformations on collections. A stream is a iterator that allows a single run over the collection it is called on. You can use streams to perform functional operations like filer or map/reduce over collections which can be streamed as individual elements using Stream objects. Streams can run sequentially or parallely as desired. The parallel mode makes use of fork/join framework and can leverage power of multiple cores. 

Some of the example of the stream class is shown below:



//From given numbers, double the even numbers and sum them
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println(numbers.stream().filter(e -> e%2 ==0)
						.mapToInt(e -> e *2)
						.sum());

In the above example, we iterate through the list and filter all the even elements and then double them and at the end sum them up. If our input is large we can use paraller stream as well sa shown below:



System.out.println(numbers.parallelStream().filter(e -> e%2 ==0)
						.mapToInt(e -> e *2)
						.sum());

The above code will leverage the power of multiple cores and provide us the faster output in case of out input is  very large. For details explaination of the stream classes you can check the article  Stream API | Java8.


Interface Default Method:

Java8 introduced the concept of default method in interfaces without breaking the existing implementation of the interface. Consider a scenario where you have an interface which is implemented by wide range of classes. Now suppose you need to introduce one more behaviour into the interface, your all system will break and to fix that you need to implement that behaviour to all the classes that extends that behaviour.  Here with option of default method, you can simply add a default method into the interface and it will be there for all the classes.

We can define default method in Interface as below:



public interface MyInterface {
    public void existingMethod();
 
    default public void newDefaultMethod() {
        System.out.println("New default method"
               + " is added in interface");
    }
}

Now if there is some class who is implementing this interface as below:



public class MyClass implements MyInterface {

    public void existingMethod() {
     // existing implementation is here…
    }
}

The above class will still compile successfully in Java8.

Detailed explaination on default method can be found in article Default Method In Interface | Java8

Happy Learning 🙂

Tags: , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.

Total Post : 80
Subscribe
Contribute Your Articles

Interview Experiences

Related Books

Like Us On Facebook

Alexa Page Rank