1. Java 8 New Features
and enhancements
Aniket Thakur
2. Interface Basics
• What we know so far
• What is an interface?
• Variables in an interface?
• Methods in an interface?
• Interface Vrs Abstract class?
3. interface A
{
void printEmployeeNames(String division);
}
interface B
{
void printEmployeeNames(String division);
}
class AB implements A,B
{
@Override
public void printEmployeeNames(String division)
{
//print employee names based on division
}
}
public class HelloWorld
{
public static void main(String args[])
{
new AB().printEmployeeNames(”Security");
}
}
Will this work?
4. Java 8 changes in interface
• Static Methods are allowed
• Eg.
interface A
{
static void printEmployeeNames(String division)
{
//print employee names based on division
}
}
5. Default Methods
• Provide default implementation of methods defined in an
interface.
• Don’t have to make changes in all concrete subclasses
implementing the interface
Eg –
interface A {
default void printEmployeeNames(String division) {
//print employee names based on division
}
}
6. interface A {
default void printEmployeeNames(String division) {
//print employee names based on division
}
}
interface B {
default void printEmployeeNames(String division) {
//print employee names based on division
}
}
class AB implements A,B {
}
//make an instance of AB and call printEmployeeNames
Will this work?
7. interface A {
default void printEmployeeNames(String division) {
//print employee names based on division
}
}
interface B {
default void printEmployeeNames(String division) {
//print employee names based on division
}
}
class AB implements A,B {
@Override
public void printEmployeeNames(String division) {
A.super.printEmployeeNames(division);//whats this?
//print employee names based on division
}
}
//make an instance of AB and call printEmployeeNames
Will this work?
8. Final local variable(effectively
final)
public void foo() {
final String x = "hello";
String y = "there";
Runnable runnable = new Runnable() {
@Override public void run() {
System.out.println(x);
System.out.println(y);
}
};
runnable.run();
}
9. Changes in HashMap
• Using Balanced trees instead of Linked List
• Improves worst case performance from O(n) to O(log n).
• Implementation in -
• java.util.HashMap,
• java.util.LinkedHashMap and
• java.util.concurrent.ConcurrentHashMap.
10. Functional Interfaces
• Interface with just one abstract method.
Eg. –
interface MyInterface {
int getAge();
}
• How about?
interface A {
boolean equals(Object obj);
int getAge();
}
11. How about?
interface A {
default void printEmployeeNames(String division) {}
static void newMethod(){}
int getAge();
}
• OR
interface A {
public boolean equals(Object obj);
default void printEmployeeNames(String division) {}
static void newMethod(){}
int getAge();
int getNewAge();
}
13. About Functional interfaces
• Any public method defined by Object, any default methods or
any static methods do not affect the functional status of an
functional interface. As long as it has just one abstract
method.
• Questions?
14. Common functional interfaces
• Part of java.util.function
• https://docs.oracle.com/javase/8/docs/api/java/util/function/
package-summary.html
• The convention used here us generic type T for type
parameter, for second type parameter the next letter U and
for a distinct return type R is used as the generic type.
15. Predicate
• Takes a single paramter of any type and returns a boolean
@FunctionalInterface // what’s this?
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the
predicate,
* otherwise {@code false}
*/
boolean test(T t);
//other methods
}
16. Consumer
• Takes a single paramter of any type and has a void return type
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
17. Supplier
• Does not take any parameter and returns any type
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
18. UnaryOperator
• Takes a single parameter of any type and returns of same type
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
19.
20. Lambda Expressions
• Lambda expression implements the abstract method in a
functional interface.
• Kind of anonymous class. Also called closures.
22. Similarities n Difference
• Block lambdas must have return statements unlike expression ones
where RHS is the return value.
• We can omit specifying argument types. It is automatically inferred
from Functional interface.
• You can have local variables, loops , case statement in you block.
• Same access rules as inner classes.
• Same goes for exception handling. You lambda expression can throw
checked exception but so must you abstract method (compatibility).
• Eg.
Runnable myRunner= () ->{
System.out.println("I am running");
};
23. Power Of Lambda expression
• What makes Lambda expressions so special?
• Deferred execution
• You can now send executable code as method argument.
• More later
24. Say hello to Generics
• lambda expression themselves cannot have generics but the functional interface that
corresponds to a lambda expression can have generics.
Eg.
public class HelloWorld {
public static void main(String args[]) {
MyInterface<String> myStringInterface = (input) -> "Hello " + input;
MyInterface<Integer> myIntInterface = (input) -> 10 + input;
System.out.println("String based lambda exp : " + myStringInterface.myFunc(”I am
Groot"));
System.out.println("Integer based labmda exp : " + myIntInterface.myFunc(14));
}
}
interface MyInterface<T> {
T myFunc(T t);
}
27. Method references
• Because Lambda expressions were not enough
• 4 types –
• Reference to a static method
• Reference to a constructor
• Reference to an instance method of an arbitrary object of a
particular type
• Reference to an instance method of a particular object
28. 1. Reference to a static
method
List<String> platforms=
Arrays.asList(“Android”,”iOS”,”Windows”,”IDontCare”);
Consumer<List<String>> methodRef1 = Collections::sort;
methodRef1.accept(platforms);
System.out.println(platforms);
• Equivalent Lambda :
Consumer<List<String>> lambdaRef1 = l -> Collections.sort(l);
29. 2. Reference to a constructor
Supplier<ArrayList<String>> methodRef2 = ArrayList::new;
List<String> newEmployeeNameList = methodRef2.get();
newEmployeeNameList.add(”Intern1");
newEmployeeNameList.add(”Intern2");
System.out.println(newEmployeeNameList);
• Equivalent Lambda :
Supplier<ArrayList> lambdaRef2 = () -> new ArrayList();
• Advice : Try not to look at LHS for functional interface types
and try to guess what kind of interface it is. Coz later we will
directly use it in method arguments. More good stuff to follow
30. 3. Referenceto an instance methodof an
arbitraryobjectof a particulartype
Predicate<String> methodRef3 = String::isEmpty;
String emtptyString = "";
System.out.println(methodRef3.test(emtptyString));
• Equivalent Lambda :
Predicate<String> lambdaRef3 = s -> s.isEmpty();
31. 4. Referenceto an instance methodof a
particularobject
String myName = "Aniket";
Predicate<String> methodRef4 = myName::contains;
System.out.println(methodRef4.test("ike"));
• Equivalent Lambda :
Predicate<String> lambda2 = s -> s.contains(“ike”);
33. Stream API
• Basically sequence of data on which you can operate.
• Three essential parts –
• Source
• Think of this as data set used to generate a stream. Depending on
this a stream can be
• Finite Or
• Infinite
• Intermediate operations
• These operations you can perform on the data set to filter our or
process your data. You can use as many as you desire. One
intermediate operation will give you stream back so that you can
perform additional intermediate operations on it.
• Terminal operations
• These operations produce final results. Only one terminal operation
is allowed per stream.
35. Operations
• Common intermediate operations :
• filter()
• distinct()
• limit() and skip()
• map()
• sorted()
• peek()
• Common terminal operations :
• allMatch()/anyMatch()/noneMatch()
• collect()
• count()
• findAny()/findFirst()
• forEach()
• min()/max()
• reduce()
None of these affect the underlying data set (Unless you do something to
change it)
39. N more…
Stream.iterate(1, n -> n+1)
.filter(x -> x%5==0)
.limit(5)
.forEach(System.out::println);
Stream.iterate(1, n -> n+1)
.filter(x -> x%5==0)
.peek(System.out::println)
.limit(5)
.forEach(System.out::println);
40. java.util.ConcurrentModificationException
• Same as iterator do not modify the underlying collection while
processing it’s stream. Else you will get -
java.util.ConcurrentModificationException
• Eg.
List<String> listForStream = new
ArrayList<>(Arrays.asList("ABC","PQR","XYZ"));
Stream<String> streamFromList =
listForStream.stream(); streamFromList.forEach(elm ->
listForStream.remove(elm));//boom
System.out.println(listForStream);
41. Last but not the least
• Other topics you can cover on your own
1. Optional class and it’s usage (Specially in Spring MVC)
2. New NIO.2 APIs – Path, Files, walking dir etc.
3. Stream for primitives – IntStream, LongStream, DoubleStream
etc
4. Parallel stream – multi threading involved
5. ExecutorService – Callable , Runnable are functional interfaces
6. New Date/Time API
42. Java SE 8 OCP Programmer
• If you already have Java 7 certification :
• http://education.oracle.com/pls/web_prod-plq-
dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:
1Z0-810
• If you have Java 6 or prior certification :
• https://education.oracle.com/pls/web_prod-plq-
dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:
1Z0-813
• First timers :
• You need to give associate level exam first :
• https://education.oracle.com/pls/web_prod-plq-
dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-
808
• Then you can give professional once :
• https://education.oracle.com/pls/web_prod-plq-
dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-
809