Java 8 Features
Java SE 8 was released in early 2014. In java 8, we have new features that are found in other programming languages like Python, Scala. eg Lamda expression.
There are many new features added like Functional Interface, Default Methods, Stream API, Date/Time API Changes Optional, Method references, etc.
We see them one by one.
Functional Interface
It is also called as Single Abstract Method interfaces (SAM Interfaces).
We are allowed to write only one abstract method inside the Interface. The @FunctionalInterface annotation is required when you define an interface with SInge Abstract method,
A functional interface is like
@FunctionalInterface
public interface ShopKeeper {
public void sellItems();
}
If an interface declares an abstract method overriding one of the public methods of java.lang.Object, it not counted as the interface’s abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere. for example, below is a perfectly valid functional interface.
@FunctionalInterface
public interface ShopKeeper
{
public void sellItems();
@Override
public String toString(); //From from Object class
@Override
public boolean equals(Object obj); //From from Object class
}
default methods are not abstract you’re free to add default methods to your functional interface as many as you like.
@FunctionalInterface
public interface ShopKeeper
{
public void sellItems();
default void calculateNetSell(){
//code
System.out.println("NetSell is : "+netSell);
}
static void CalculateRemainingItems(){
//code
//codeSystem.out.println("remainingItems: "+remainingItems);
}
}
forEach() method in Iterable interface
While iterating through a Collection, we need to create an Iterator whose whole purpose is to iterate over, and then we have business logic in a loop for each of the elements in the Collection. We might get ConcurrentModificationException if the iterator is not used properly.
Java 8 has 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 independent level.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
import java.lang.Integer;
public class ForEachexample{
public static void main(String[] args) {
List list = new ArrayList();
for(int i=0; i<10 i="" iterator="" mylist.add="" nteger=""> it = list.iterator();
while(it.hasNext()){
Integer i = it.next();
System.out.println("Iterator Value::"+i);
}
//traversing forEach method of Iterable with anonymous class
list.forEach(new Consumer() {
public void accept(Integer value) {
System.out.println("anonymous class Value::"+value);
}
});
//traversing with Consumer interface implementation
MyConsumer action = new MyConsumer();
list.forEach(action);
}
}
//Consumer implementation that can be reused
class MyConsumer implements Consumer{
public void accept(Integer value) {
System.out.println("value for consumer ::"+value);
}
}
10>
Default and static methods in Interfaces
Java 8 allows you to add non-abstract methods in interfaces. These methods must be declared default methods.
Default methods were introduced in java 8 to enable the functionality of lambda expression.
We can use the default and static keyword to create interfaces with method implementation. forEach method implementation in the Iterable interface is:
default void forEach(Consumer action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
@FunctionalInterface
public interface ShopKeeper
{
public void sellItems();
default void calculateNetSell(){
//code
System.out.println("NetSell is : "+netSell);
}
}
Java doesn’t provide multiple inheritances in Classes because it leads to Diamond Problem. So how it will be handled with interfaces now since interfaces are now similar to abstract classes
Optional in Java SE 8
Optional is not a new concept, but an old one which often results in polarized opinions.
The class itself is a simple box around an object, which has a special marker for empty instead of using null:
Optional optional = Optional.of("CoreJava");
Optional empty = Optional.empty()
The goal of the class is to reduce the need to use null. Instead, Optional.empty() takes the place of null. One way to think of it is as a collection that holds either zero or one object.
When you want to get the data out of the optional, there is a nice simple method, get(), but this will throw an exception if the optional is empty. In most cases, you will want to call one of the other methods, for example, to return a default value:
Optional employeeResult = findEmployee(name);
Employee employee = employeeResult.orElse(Employee.MANAGER);
One approach to using Optional is to use it everywhere in your entire codebase and eliminate null altogether. Use cases.
It is very useful when used as a return type from an operation where previously you might have returned null
Collection API improvements
Some new methods added in Collection API are:
Iterator default method forEachRemaining(Consumer action) to perform the given action for each remaining element until all elements have been processed or the action throws an exception.
Collection default method removeIf(Predicate filter) to remove all of the elements of this collection that satisfy the given predicate.
Collection spliterator() method returning Spliterator instance that can be used to traverse elements sequentially or parallel.
Map replaceAll(), compute(), merge() methods.
Performance Improvement for HashMap class with Key Collisions
Concurrency API improvements
Some important concurrent API enhancements are:
ConcurrentHashMap compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.
CompletableFuture that may be explicitly completed (setting its value and status). Executors newWorkStealingPool() method to create a work-stealing thread pool using all available processors as its target parallelism level.
Java IO improvements
Files.list(Path dir) that returns a lazily populated Stream, the elements of which are the entries in the directory.
Files.lines(Path path) that reads all lines from a file as a Stream.
Files.find() that returns a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.
BufferedReader.lines() that return a Stream, the elements of which are lines read from this BufferedReader.
Core API improvements
1). ThreadLocal static method withInitial(Supplier supplier) to create instance easily.
2). Comparator interface has been extended with a lot of default and static methods for natural ordering, reverse order etc. min(), max() and sum() methods in Integer, Long and Double wrapper classes.
3). logicalAnd(), logicalOr() and logicalXor() methods in Boolean class.
4). ZipFile.stream() method to get an ordered Stream over the ZIP file entries. Entries appear in the Stream in the order they appear in the central directory of the ZIP file.
5). Several utility methods in Math class.
6). jjs command is added to invoke Nashorn Engine.
7). jdeps command is added to analyze class files.
8). JDBC-ODBC Bridge has been removed.
9). PermGen memory space has been removed
That's all about Java8 Features.
0 Comments
Post a Comment