Friday, 22 April 2016

New features of Java 1.8 (Java 8)


New features of Java 8

1. Lamda Expressions
It reduces the code, such as in an anonymous inner class.

Example 1 (Before Java 8)
Runnable oldRunner = new Runnable(){
    public void run(){
        System.out.println("I am running");
    }
};

Example 1 (After Java 8)
Runnable java8Runner = () ->{
    System.out.println("I am running");
};


Example 2 (Before Java 8)
Comparator c = new Comparator() {
    public int compare(Object a, Object b) {
        return Integer.compare(a.length(), b.length());
   }
}

Example 2 (After Java 8)
Comparator c = (a, b) -> Integer.compare(a.length(), b.length());



2. Streams collection types
A stream represents a sequence of elements and supports different kind of operations.
Lists and Sets support new methods stream() and parallelStream() to either create a sequential or a parallel stream. Parallel streams are capable of operating on multiple threads.

List<String> myList = Arrays.asList("a1", "c1", "b1", "b2", "c2");

myList
    .stream()
    .filter(s -> s.startsWith("c"))
    .map(String::toUpperCase)
    .sorted()
    .forEach(System.out::println);

// C1
// C2


3. Functional Interfaces
These interfaces can contain some default methods which need not be implemented and can run directly from the interface.


4. Date/Time changes
The Date/Time API is moved to java.time package and Joda time format is used.
Most classes are Threadsafe and immutable.


5. Nashorn - Run JS on JVM
This is the javascript engine that enables us to run javascript to run on a  jvm.
It is compatible with Node.js applications while also allowing actual Java libraries to be called by the javascript code running on server.


6. StringJoiner
Utility method to construct a string with desired delimiter
StringJoiner strJoiner = new StringJoiner(",");
strJoiner.add("Hello").add("Bye");
System.out.println(strJoiner);
// Hello,Bye

Others
  • Reflection API now support TypeName, GenericString, etc.
  • Comparator methods like reversed, comparing and thenComparing have been added which allow easy customization of comparison of multiple fields.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.