SlideShare a Scribd company logo
JDK8
The New Features
Language
Lambdas and functional
interfaces
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello from thread");
}
}).run();
new Thread(() -> System.out.println("Hello from thread")).run()
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
Lambdas and functional
interfaces
Arrays.asList("a", "b", "d").sort((e1, e2) -> e1.compareTo(e2));
Arrays.asList("a", "b", "d").sort(
(String e1, String e2) -> e1.compareTo(e2));
Arrays.asList("a", "b", "d").sort(
(e1, e2) -> {
int result = e1.compareTo(e2);
return result;
});
Default methods
interface DefaultInterface {
void show();
default void display() {
System.out.println("Displaying something");
}
}
But … why ??
Default methods
package java.lang;
public interface Iterable<T> {
void forEach(Consumer<? super T> action);
}
Core interfaces have new methods
This breaks backwards compatibility
package java.lang;
public interface Iterable<T> {
default void forEach(Consumer<? super T> action) {
for (T t : this) { action.accept(t); }
}
}
This doesn’t
Static interface methods
interface MyInterface {
void method1();
static void method2() { System.out.println("Hello from static");
}
}
...
MyInterface.method2();
Keep interface related helper methods in the same class rather
than creating a new one
Method references
Static reference
class Example {
public static void main(String[] args) {
String[] str = {"one", "two", "3", "four"};
Arrays.sort(str, Example::compareByLength);
Arrays.sort(str, (s1, s2) -> s1.length() - s2.length());
}
public static int compareByLength(String s1, String s2) {
return s1.length() - s2.length();
}
}
Method references
Instance reference
@FunctionalInterface // New JDK8 interface
public interface Supplier {
T get();
}
public String function(Supplier<String> supplier) {
return supplier.get();
}
public void example() {
final String x = "A string";
function(() -> x.toString());
function(x::toString);
}
Method references
Constructor reference
class Car {}
class Example {
public static Car createCar(Supplier supplier) {
return supplier.get();
}
public static void repair(Car car) {}
public static void main(String[] args) {
Car car = createCar(Car::new);
List cars = Arrays.asList(car);
cars.forEach(Example::repair);
}
}
Repeating annotations
class RepeatingAnnotations {
public @interface Filters { // A hidden filter holder
Filter[] value();
}
@Repeatable(Filters.class)
public @interface Filter {
String value();
}
@Filter("filter1")
@Filter("filter2")
public void filterredMethod() {}
}
Repeat yourself
Extended annotations
class Annotations {
public @interface NotEmpty {}
public static class Holder<@NonEmpty T> extends @NonEmpty Object{
public void method() throws @NonEmpty Exception {}
}
public static void main(String[] args) {
final Holder<String> holder = new @NonEmpty Holder<String>();
@NonEmpty Collection<@NonEmpty String> strings =
new ArrayList<>();
}
}
Annotate anything
Libraries
Optional
Optional<String> name = Optional.ofNullable(null);
System.out.println("Name is set? " + name.isPresent() );
System.out.println("Name: " + name.orElseGet( () -> "[none]" ));
System.out.println(name.map( s -> "Hey " + s + "!" )
.orElse("Hey Stranger!"));
java.util.Optional
Name is set? false
Name: [none]
Hey Stranger!
Streams
for (Student student : students) {
if (student.getName().startsWith("A")){
names.add(student.getName());
}
}
java.util.stream
List<string> names =
students.stream()
.map(Student::getName)
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
The old way
The Java8 way
Streams
java.util.stream
int sum =
students.parallelStream()
.map(Student::getName)
.filter(name -> name.startsWith("A"))
.mapToInt(String::length)
.sum();
System.out.println(
Arrays.asList("One", "Two", "Three")
.stream().collect(Collectors.groupingBy(String::length))
);
{3=[One, Two], 5=[Three]}
Date/Time API
JSR 310 - java.time
Date/Time API
JSR 310 - java.time
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 2);
LocalTime now = LocalTime.now();
LocalTime later = now.plus(2, HOURS);
The old way
The Java8 way
Nashorn
JavaScript engine
• Rhino replacement
• Faster (2 to 10x performance boost)
• Full ECMAScript 5.1 support + extensions
• Compiles JS to Java bytecode
Nashorn
Example
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
System.out.println(engine.getClass().getName() );
System.out.println("Result:" + engine.eval(
"function f() { return 1; }; f() + 1;" ) );
jdk.nashorn.api.scripting.NashornScriptEngine
Result: 2
Nashorn
Performance
V8 Chrome 31
Spidermonkey F
F 25.0.1
Nashorn
Octane 2.0 14 474 10 066 9 307
Sunspider 1.0.2 220.8 ms 246.5 ms 256.2 ms
http://wnameless.wordpress.com/2013/12/10/javascript-engine-benchmarks-nashorn-vs-v8-vs-spidermonkey/
Base64
Finally … java.util.Base64
final String encoded = Base64
.getEncoder()
.encodeToString( text.getBytes( StandardCharsets.UTF_8 ));
final String decoded = new String(
Base64.getDecoder().decode(encoded),
StandardCharsets.UTF_8);
Tools
jjs
function f() {
return 1;
};
print(f() + 1);
jjs file.js
2
file.js
command
output
Nashorn runner
jdepts
Dependency analyzer
jdeps jdom2-2.0.5.jar
jdom2-2.0.5.jar ->
/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home/jre/lib/
rt.jar
org.jdom2 (jdom2-2.0.5.jar)
-> java.io
-> java.lang
-> java.net
-> java.util
-> java.util.concurrent
org.jdom2.adapters (jdom2-2.0.5.jar)
-> java.lang
-> java.lang.reflect
-> javax.xml.parsers
…
command
output
JVM
Metaspace
Thank you :)

More Related Content

PDF
Java 8 - project lambda
PPTX
Java Generics
PPTX
Lambda functions in java 8
PPT
Java Generics for Dummies
PDF
Java Class Design
PDF
Java 8 Lambda Expressions
PDF
ScalaFlavor4J
PDF
Lombokの紹介
Java 8 - project lambda
Java Generics
Lambda functions in java 8
Java Generics for Dummies
Java Class Design
Java 8 Lambda Expressions
ScalaFlavor4J
Lombokの紹介

What's hot (20)

PDF
Coding Guidelines - Crafting Clean Code
PDF
Swift, functional programming, and the future of Objective-C
PDF
Important java programs(collection+file)
PPT
Collection Core Concept
PPT
Collections Framework
PPT
Initial Java Core Concept
PPT
Jhtp5 20 Datastructures
PPTX
Java and XML Schema
TXT
Xxxx
KEY
Why Learn Python?
PDF
Java VS Python
PPT
JDBC Core Concept
PDF
Understanding static analysis php amsterdam 2018
PDF
Haskell 101
PDF
Developing Applications with MySQL and Java for beginners
PDF
DCN Practical
PDF
Advanced Debugging Using Java Bytecodes
PDF
Java Concurrency by Example
PDF
The Ring programming language version 1.8 book - Part 37 of 202
PPTX
Use of Apache Commons and Utilities
Coding Guidelines - Crafting Clean Code
Swift, functional programming, and the future of Objective-C
Important java programs(collection+file)
Collection Core Concept
Collections Framework
Initial Java Core Concept
Jhtp5 20 Datastructures
Java and XML Schema
Xxxx
Why Learn Python?
Java VS Python
JDBC Core Concept
Understanding static analysis php amsterdam 2018
Haskell 101
Developing Applications with MySQL and Java for beginners
DCN Practical
Advanced Debugging Using Java Bytecodes
Java Concurrency by Example
The Ring programming language version 1.8 book - Part 37 of 202
Use of Apache Commons and Utilities
Ad

Viewers also liked (7)

PPTX
JDK8 Streams
PPTX
new features in jdk8
PPTX
New features in Java 7
PPT
Java 7 new features
PDF
New Features Of JDK 7
PDF
Java 5 and 6 New Features
PPTX
New Features in JDK 8
JDK8 Streams
new features in jdk8
New features in Java 7
Java 7 new features
New Features Of JDK 7
Java 5 and 6 New Features
New Features in JDK 8
Ad

Similar to JDK 8 (20)

PPTX
What is new in Java 8
PDF
Productive Programming in Java 8 - with Lambdas and Streams
PPTX
Nice to meet Kotlin
PDF
Sam wd programs
PDF
6. Generics. Collections. Streams
PDF
Scala - en bedre og mere effektiv Java?
PPTX
Basic java, java collection Framework and Date Time API
PPTX
Java generics
PDF
Scala vs Java 8 in a Java 8 World
PPTX
A topology of memory leaks on the JVM
PDF
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
PDF
JEEConf 2017 - Having fun with Javassist
PPTX
Programing with java for begniers .pptx
PDF
PDF
Kotlin Bytecode Generation and Runtime Performance
PDF
JavaOne 2016 - Learn Lambda and functional programming
PDF
OrderTest.javapublic class OrderTest {       Get an arra.pdf
PDF
Scala - en bedre Java?
PDF
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
DOC
What is new in Java 8
Productive Programming in Java 8 - with Lambdas and Streams
Nice to meet Kotlin
Sam wd programs
6. Generics. Collections. Streams
Scala - en bedre og mere effektiv Java?
Basic java, java collection Framework and Date Time API
Java generics
Scala vs Java 8 in a Java 8 World
A topology of memory leaks on the JVM
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
JEEConf 2017 - Having fun with Javassist
Programing with java for begniers .pptx
Kotlin Bytecode Generation and Runtime Performance
JavaOne 2016 - Learn Lambda and functional programming
OrderTest.javapublic class OrderTest {       Get an arra.pdf
Scala - en bedre Java?
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf

Recently uploaded (20)

PPTX
Transform Your Business with a Software ERP System
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
ai tools demonstartion for schools and inter college
PPTX
assetexplorer- product-overview - presentation
PDF
Digital Strategies for Manufacturing Companies
PDF
System and Network Administration Chapter 2
PDF
Nekopoi APK 2025 free lastest update
Transform Your Business with a Software ERP System
Design an Analysis of Algorithms I-SECS-1021-03
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Computer Software and OS of computer science of grade 11.pptx
Odoo Companies in India – Driving Business Transformation.pdf
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Which alternative to Crystal Reports is best for small or large businesses.pdf
Upgrade and Innovation Strategies for SAP ERP Customers
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Navsoft: AI-Powered Business Solutions & Custom Software Development
Reimagine Home Health with the Power of Agentic AI​
2025 Textile ERP Trends: SAP, Odoo & Oracle
ai tools demonstartion for schools and inter college
assetexplorer- product-overview - presentation
Digital Strategies for Manufacturing Companies
System and Network Administration Chapter 2
Nekopoi APK 2025 free lastest update

JDK 8

  • 3. Lambdas and functional interfaces new Thread(new Runnable() { @Override public void run() { System.out.println("Hello from thread"); } }).run(); new Thread(() -> System.out.println("Hello from thread")).run() @FunctionalInterface public interface Runnable { public abstract void run(); }
  • 4. Lambdas and functional interfaces Arrays.asList("a", "b", "d").sort((e1, e2) -> e1.compareTo(e2)); Arrays.asList("a", "b", "d").sort( (String e1, String e2) -> e1.compareTo(e2)); Arrays.asList("a", "b", "d").sort( (e1, e2) -> { int result = e1.compareTo(e2); return result; });
  • 5. Default methods interface DefaultInterface { void show(); default void display() { System.out.println("Displaying something"); } } But … why ??
  • 6. Default methods package java.lang; public interface Iterable<T> { void forEach(Consumer<? super T> action); } Core interfaces have new methods This breaks backwards compatibility package java.lang; public interface Iterable<T> { default void forEach(Consumer<? super T> action) { for (T t : this) { action.accept(t); } } } This doesn’t
  • 7. Static interface methods interface MyInterface { void method1(); static void method2() { System.out.println("Hello from static"); } } ... MyInterface.method2(); Keep interface related helper methods in the same class rather than creating a new one
  • 8. Method references Static reference class Example { public static void main(String[] args) { String[] str = {"one", "two", "3", "four"}; Arrays.sort(str, Example::compareByLength); Arrays.sort(str, (s1, s2) -> s1.length() - s2.length()); } public static int compareByLength(String s1, String s2) { return s1.length() - s2.length(); } }
  • 9. Method references Instance reference @FunctionalInterface // New JDK8 interface public interface Supplier { T get(); } public String function(Supplier<String> supplier) { return supplier.get(); } public void example() { final String x = "A string"; function(() -> x.toString()); function(x::toString); }
  • 10. Method references Constructor reference class Car {} class Example { public static Car createCar(Supplier supplier) { return supplier.get(); } public static void repair(Car car) {} public static void main(String[] args) { Car car = createCar(Car::new); List cars = Arrays.asList(car); cars.forEach(Example::repair); } }
  • 11. Repeating annotations class RepeatingAnnotations { public @interface Filters { // A hidden filter holder Filter[] value(); } @Repeatable(Filters.class) public @interface Filter { String value(); } @Filter("filter1") @Filter("filter2") public void filterredMethod() {} } Repeat yourself
  • 12. Extended annotations class Annotations { public @interface NotEmpty {} public static class Holder<@NonEmpty T> extends @NonEmpty Object{ public void method() throws @NonEmpty Exception {} } public static void main(String[] args) { final Holder<String> holder = new @NonEmpty Holder<String>(); @NonEmpty Collection<@NonEmpty String> strings = new ArrayList<>(); } } Annotate anything
  • 14. Optional Optional<String> name = Optional.ofNullable(null); System.out.println("Name is set? " + name.isPresent() ); System.out.println("Name: " + name.orElseGet( () -> "[none]" )); System.out.println(name.map( s -> "Hey " + s + "!" ) .orElse("Hey Stranger!")); java.util.Optional Name is set? false Name: [none] Hey Stranger!
  • 15. Streams for (Student student : students) { if (student.getName().startsWith("A")){ names.add(student.getName()); } } java.util.stream List<string> names = students.stream() .map(Student::getName) .filter(name -> name.startsWith("A")) .collect(Collectors.toList()); The old way The Java8 way
  • 16. Streams java.util.stream int sum = students.parallelStream() .map(Student::getName) .filter(name -> name.startsWith("A")) .mapToInt(String::length) .sum(); System.out.println( Arrays.asList("One", "Two", "Three") .stream().collect(Collectors.groupingBy(String::length)) ); {3=[One, Two], 5=[Three]}
  • 17. Date/Time API JSR 310 - java.time
  • 18. Date/Time API JSR 310 - java.time Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 2); LocalTime now = LocalTime.now(); LocalTime later = now.plus(2, HOURS); The old way The Java8 way
  • 19. Nashorn JavaScript engine • Rhino replacement • Faster (2 to 10x performance boost) • Full ECMAScript 5.1 support + extensions • Compiles JS to Java bytecode
  • 20. Nashorn Example ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); System.out.println(engine.getClass().getName() ); System.out.println("Result:" + engine.eval( "function f() { return 1; }; f() + 1;" ) ); jdk.nashorn.api.scripting.NashornScriptEngine Result: 2
  • 21. Nashorn Performance V8 Chrome 31 Spidermonkey F F 25.0.1 Nashorn Octane 2.0 14 474 10 066 9 307 Sunspider 1.0.2 220.8 ms 246.5 ms 256.2 ms http://wnameless.wordpress.com/2013/12/10/javascript-engine-benchmarks-nashorn-vs-v8-vs-spidermonkey/
  • 22. Base64 Finally … java.util.Base64 final String encoded = Base64 .getEncoder() .encodeToString( text.getBytes( StandardCharsets.UTF_8 )); final String decoded = new String( Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
  • 23. Tools
  • 24. jjs function f() { return 1; }; print(f() + 1); jjs file.js 2 file.js command output Nashorn runner
  • 25. jdepts Dependency analyzer jdeps jdom2-2.0.5.jar jdom2-2.0.5.jar -> /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home/jre/lib/ rt.jar org.jdom2 (jdom2-2.0.5.jar) -> java.io -> java.lang -> java.net -> java.util -> java.util.concurrent org.jdom2.adapters (jdom2-2.0.5.jar) -> java.lang -> java.lang.reflect -> javax.xml.parsers … command output

Editor's Notes

  • #4: Functional interface can have only one abstract method Annotation is optional
  • #16: Real-world functional-style programming into the Java
  • #17: Parallel stream Arrays, BufferedReader
  • #18: New API, Safety (enums), Readability