Java 8 - new features and enhancements with examples

Java 8 introduced lot of exiting new features and enhancements which are useful for developers . This article covers these features ( functional interfaces, lambda expression, method reference, Stream API, default and static methods in interface and more ) with short and simple examples.

  1. Functional Interface ( Annotation : @FunctionalInterface )
  2. default and static methods for interfaces
  3. Lambda Expression
  4. Method reference
  5. forEach() method for Iterable
  6. Stream API for Collections
  7. Concurrency API enhancements
  8. Date-Time packages
  9. Nashorn - JavaScript Engine
  10. Miscellaneous enhancements

1) Functional Interface ( Annotation : @FunctionalInterface )

Java 8 came up with new type of interface called Functional Interface which is any interface with exactly one abstract method. You can mark an interface with @FunctionalInterface to make sure it has only abstract method.

java.lang.Runnable, java.util.Comparator can be treated as Functional Interfaces since they have only abstract method in them.

Note : Any interface is treated as functional interface if it has exactly one abstract method even it is not annotated with @FunctionalInterface.

Examples :

@FunctionalInterface
public interface Person {
	void talk(String statement);
}
@FunctionalInterface
public interface Person {
	void talk(String statement);
	
	default void method2() {
		System.out.println("default method");
	}
	
	static void method3() {
		System.out.println("static method");
	}
}

2) default and static methods for interfaces

Now interfaces can have methods with implementation provided that they are marked with keywords default or static.

Example :

interface Software {
  void install();

  void run();

  default void log() {
    System.out.println("logged");
  }

  static void checkStatus(String componentName) {
    System.out.println("Checking the status of " + componentName);
  }
}

3) Lambda Expression

Lambda Expression is a new features in Java 8 , which enables you to provide implementation of functional interface in an easy and compact way.

Syntax :  ( arg1, arg2 , ... ) -> { // body of one and only abstract method of interface }

Examples :

Person p = (stmt) -> { System.out.println("Person said " + stmt) };  // method body with curly braces

Person p = (stmt) -> System.out.println("Person said " + stmt);    // single line method body without curly braces

Full Example @ Java 8 - Lambda Expression example

4) Method reference

Method reference is another way of passing or assigning reference to Functional Interface . It is also more compact way which can replace Lambda expression when expression refers to an existing method simply.

Example :

class Employee {
  void hello(String name) {
    System.out.println("Employee name is " + name);
  }
  void work() {
    System.out.println("working");
  }
}

@FunctionalInterface
interface Person {
  void say(String);
}
Person person = Employee::hello;
person.say("Prashanth"); // output : Employee name is Prashanth

5) forEach() method for Iterable

Now iterating through any Iterable such as List is made easy. Before introduction of this feature in Java 8, we used to iterate over a Collection such as List either by using a for loop or by using combination of iterator and while loop, but now iterating is made easy and compact so that it can even be written in single line.

Example :

List list = new ArrayList();

// adding elements to list
for(int i=0; i<10; i++) list.add(i);

// iterate using new forEach() with lambda expression
list.forEach(a -> System.out.print(a));

This is just one way of forEach. We have more simple ways to do forEach() in Java 8.

Full Example @ Java 8 - forEach() with full example

6) Stream API for Collections

Java 8 introduced new package java.util.stream which allow us to perform operations like filter , map, reduce on data in collections. You would find this Stream API very much useful if you are a developer working with collections a lot.

Collections interface has been extended with two methods namely stream() and parallelStream() default methods which returns Stream object for sequential and parallel execution.

Example :

List<Integer> list = new ArrayList<>();
 
for(int i=0; i<10; i++) list.add(i); 
    
// Sequntial Stream for list 
Stream<Integer> sequentialStream = list.stream();

// Filter list using stream api
Stream<Integer> evenListUsingSequntialStream = sequentialStream.filter(a -> a%2 == 0);
evenListUsingSequntialStream.forEach(a -> System.out.print(a + " "));

System.out.println();

// Parallel stream for list
Stream<Integer> parallelStream = list.parallelStream();

// Filter list using stream api
Stream<Integer> evenListUsingParallelStream = parallelStream.filter(a -> a%2 == 0);
evenListUsingParallelStream.forEach(a -> System.out.print(a + " "));

Full Example @ Java 8 – Stream API and its benefits with simple examples

7) Concurrency API enhancements

Java 8 introduced new classes and methods for java. util.concurrent package. Few of the improvements are as follows :

  •  newWorkStealingPool() in Executors class : Creates a work steeling thread pool using available processors as its target parallelism level.
  • interface CompletionStage : A stage of an asynchronous computation which performs action upon completion of another CompletionStage.
  • class CompletableFuture : A Future, an implementation of CompletionStage, that can be completed by setting its value and status explicitly, and giving the turn to dependent functions and action to trigger upon its completion.
  • ConcurrentHashMap class introduces over 30 new methods such as forEach methods (forEach, forEachKey, forEachValue and forEachEntry ), search methods (search, searchKeys, searchValues, searchEntries ) and lot of reduce methods ( reduce, reduceToDouble etc ), as a result of newly added streams and lambda expression facilities in Java 8.

8) Date-Time packages

Until Java 7, there was not much flexibility and consistency when working with date and time which comes in classes such as java.util.Date , java.util.Calander, java.text.* etc. and most developers used to go with Joda-Time , an open source date and time library.

Now Java 8 streamlines date and time by introducing new packages java.time, java.time.chrono, java.time.format , java.time.temporal ,java.time.zone to work with date, time, time zones, formats etc , which offer lot of flexibility so that there won't be a need to go for third party libraries.

9) Nashorn - JavaScript Engine

Java Nashorn is a new javascript engine introduced in Java 8 which replaces existing Rhino javascript engine. You can execute JavaScript dynamically by embedding in Java source code.
Java 8 also provides new command-line tool jjs to execucte JavaScript.

Example :

ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");
Reader reader = new FileReader("resources/demo.js");
engine.eval(reader);

Full ExampleJava + JavaScript with example

10) Miscellaneous enhancements

  • jdeps command line tool is provided for analyzing class files
  • jjs command line tool to execute JavaScript files
  • Unicode Enhancements, including support for Unicode 6.2.0
  • The JDBC-ODBC Bridge has been removed
  • JDK 8 includes Java DB 10.10
  • JAXP 1.6 has been introduced in Java 8
  • PermGen space has been removed
  • Enhancements to Java IO package
  • Several security enhancements such as stronger algirithms for password encryptions, keystore enhancements etc
  • Improved type inference
  • Performance Improved for HashMaps with Key Collisions

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

www.000webhost.com