Tuesday 26 September 2017

Java 8 features

Java 8 new features

  1. forEach() method in Iterable interface
  2. default and static methods in Interfaces
  3. Functional Interfaces and Lambda Expressions
  4. Java Time API
  5. Collection API improvements
  6. Java IO improvements
  7. Miscellaneous Core API improvements
  8. Concurrency API improvements
  9. Java Stream API for Bulk Data Operations

forEach() method in Iterable interface

Remember ConcurrentModificationException if iterator is not used properly, no need to worry for it .
Java 8 has introduced forEach method in java.lang.Iterable interface so that while writing code we focus on business logic only. forEach method takes java.util.function.Consumer object as argument, so it helps in having our business logic at a separate location that we can reuse.

List<String> names = new ArrayList<>();
items.add("Ashwin");
items.add("Samar");
items.add("Omer");
items.add("Sachin");
items.add("Sandeep");

//lambda
items.forEach(item->System.out.print(item +"\t"));
//Output: Ashwin Samar Omer Sachin Sandeep

//Checking condition
items.forEach(item->{
    if("Ashwin".equals(item)){
        System.out.println(item);
    }
});
//Output : Ashwin

//method reference
items.forEach(System.out::println);
//Output: Ashwin Samar Omer Sachin Sandeep 

//Using Stream and filter
items.stream()
    .filter(s->s.contains("Samar"))
    .forEach(System.out::println);

//Output: Samar

default and static methods in Interfaces

Before Java 8, interfaces could have only public abstract methods. It was not possible to add new functionality to the existing interface without forcing all implementing classes to create an implementation of the new methods, nor it was possible to create interface methods with an implementation.

Starting with Java 8, interfaces can have static and default methods that, despite being declared in an interface, have a defined behavior.

Static Method
Consider the following method of the interface (let’s call this interface Person):

static String nationality() {
    return "Indian";
}

The static producer() method is available only through and inside of an interface. It can’t be overridden by an implementing class.
To call it outside the interface the standard approach for static method call should be used

String nationality = Person.nationality();

No comments:

Post a Comment