SlideShare a Scribd company logo
What's New in JAVA 8
Sandeep Kumar Singh
Solution Architect
Agenda
• New Features in Java language
• New Features in Java libraries
• New JAVA Tools
New Features in Java language
• Lambda expression
• Method and Constructor References
• Default Interface method
• Repeating annotations
• Improved Type Inference
Lambda expression
• Enable to treat functionality as a method
argument, or code as data.
• Lambda expressions express instances of
single-method interfaces (referred to as
functional interfaces) more compactly
Examples
List<String> strList = Arrays.asList("peter", "anna",
"mike", "xenia");
for(String name : strList){
System.out.println(name);
}
Arrays.asList( "peter", "anna", "mike", "xenia"
).forEach( e -> System.out.println( e ) );
List<String> names = Arrays.asList("peter", "anna",
"mike", "xenia");
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return b.compareTo(a);
}
});
Collections.sort(names, (a, b) ->
b.compareTo(a));
JAVA 7
JAVA 7
JAVA 8
JAVA 8
Method and Constructor References
• Provides the useful syntax to refer directly to
exiting methods or constructors of Java classes
or objects.
• Java 8 enables you to pass references of
methods or constructors via the :: keyword
Examples (Method and Constructor References)
class ComparisonProvider {
public int compareByName(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
public static int compareByAge(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
// Reference to an instance method
ComparisonProvider myComparisonProvider = new
ComparisonProvider();
Arrays.sort(rosterAsArray,
myComparisonProvider::compareByName);
// Reference to a static method
Arrays.sort(rosterAsArray, ComparisonProvider
::compareByName);
class Person {
String firstName;
String lastName;
Person() {}
Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
interface PersonFactory<P extends Person> {
P create(String firstName, String lastName);
}
PersonFactory<Person> personFactory =
Person::new;
Person person = personFactory.create("Peter",
"Parker");
Method References Constructor References
Default Interface method
• Enable to add new functionality to an
interface by utilizing the “default” keyword.
• This is different from abstract methods as they
do not have a method implementation
• This ensures binary compatibility with code
written for older versions of those interfaces.
Examples (Default Interface method)
interface Formula {
double calculate(int a);
default double sqrt(int a) {
return Math.sqrt(a);
}
}
Formula formula = new Formula() {
@Override
public double calculate(int a) {
return sqrt(a * 10);
}
};
formula.calculate(10); // 10.0
formula.sqrt(4); //2
Repeating annotations
• Repeating Annotations provide the ability to
apply the same annotation type more than
once to the same declaration or type use.
@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour="23")
public void doPeriodicCleanup() { ... }
@Alert(role="Manager")
@Alert(role="Administrator")
public class UnauthorizedAccessException extends
SecurityException { ... }
Improved Type Inference
• The Java compiler takes advantage of target
typing to infer the type parameters of a
generic method invocation.
• The target type of an expression is the data
type that the Java compiler expects depending
on where the expression appears
Examples (Improved Type Inference)
class Value< T > {
public static< T > T defaultValue() {
return null;
}
public T getOrDefault( T value, T defaultValue )
{
return ( value != null ) ? value : defaultValue;
}
}
public class TypeInference {
public static void main(String[] args) {
final Value< String > value = new Value<>();
value.getOrDefault( "22",
Value.<String>defaultValue() );
}
}
public class Value< T > {
public static< T > T defaultValue() {
return null;
}
public T getOrDefault( T value, T defaultValue
) {
return ( value != null ) ? value : defaultValue;
}
}
public class TypeInference {
public static void main(String[] args) {
final Value< String > value = new Value<>();
value.getOrDefault( "22",
Value.defaultValue() );
}
}
JAVA 7 JAVA 8
New Features in Java libraries
• Optional
• Streams
• Date/Time API
• Nashorn JavaScript engine
• Base64 Encoder/Decoder
• Parallel Arrays
Optional (a solution to NullPointerExceptions)
• Optional is a simple container for a value
which may be null or non-null.
• It provides a lot of useful methods so the
explicit null checks have no excuse anymore.
Example 1 :-
Optional<String> optional = Optional.of("bam");
optional.isPresent(); // true
optional.get(); // "bam"
optional.orElse("fallback"); // "bam”
optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b“
Example 2 :-
Optional< String > fullName = Optional.ofNullable( null );
System.out.println( "Full Name is set? " + fullName.isPresent() ); //Full Name is set? false
System.out.println( "Full Name: " + fullName.orElseGet( () -> "[none]" ) ); // Full Name: [none]
System.out.println( fullName.map( s -> "Hey " + s + "!" ).orElse( "Hey Stranger!" ) ); //Hey Stranger!
Streams
• Stream API is integrated into the Collections
API, which enables bulk operations on
collections, such as sequential or parallel map-
reduce transformations.
int max = 1000000;
List<String> values = new ArrayList<>(max);
for (int i = 0; i < max; i++) {
UUID uuid = UUID.randomUUID();
values.add(uuid.toString());
}
Example 1 (Sequential Sort):-
long count = values.stream().sorted().count();
System.out.println(count); // sequential sort took: 899 ms
Example 2 (Parallel Sort) :-
long count = values.parallelStream().sorted().count();
System.out.println(count); // parallel sort took: 472 ms
Date/Time API
• The Date-Time package, java.time, introduced in
the Java SE 8 release
• Provides a comprehensive model for date and
time and was developed under JSR 310: Date
and Time API.
• Although java.time is based on the International
Organization for Standardization (ISO) calendar
system, commonly used global calendars are
also supported.
Examples (Date/Time API)
Example1 (Clock) :-
final Clock clock = Clock.systemUTC();
System.out.println( clock.instant() ); //2015-08-26T15:19:29.282Z
System.out.println( clock.millis() ); //1397315969360
Example2 (Timezones) :-
System.out.println(ZoneId.getAvailableZoneIds()); //prints all available timezone ids
System.out.println(ZoneId.of("Europe/Berlin").getRules()); // ZoneRules[currentStandardOffset=+01:00]
System.out.println(ZoneId.of("Brazil/East").getRules()); // ZoneRules[currentStandardOffset=-03:00]
Example3 (LocalTime) :-
LocalTime late = LocalTime.of(23, 59, 59);
System.out.println(late); // 23:59:59
Example4 (LocalDate) :-
LocalDate independenceDay = LocalDate.of(2015, Month.AUGUST, 15);
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek); // SATURDAY
Example5 (LocalDateTime) :-
LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);
DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
System.out.println(dayOfWeek); // WEDNESDAY
Base64 Encoder/Decoder
• Support of Base64 encoding has made its way
into Java standard library with Java 8 release.
final String text = "Base64 finally in Java 8!";
final String encoded = Base64.getEncoder() .encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
System.out.println( encoded ); // QmFzZTY0IGZpbmFsbHkgaW4gSmF2YSA4IQ==
final String decoded = new String( Base64.getDecoder().decode( encoded ), StandardCharsets.UTF_8 );
System.out.println( decoded ); // Base64 finally in Java 8!
Parallel Arrays
• Java 8 release adds a lot of new methods to
allow parallel arrays processing
long[] arrayOfLong = new long [ 20000 ];
Arrays.parallelSetAll( arrayOfLong, index -> ThreadLocalRandom.current().nextInt( 1000000 ) );
Arrays.stream( arrayOfLong ).limit( 10 ).forEach( i -> System.out.print( i + " " ) );
System.out.println();
// 591217 891976 443951 424479 766825 351964 242997 642839 119108 552378
Arrays.parallelSort( arrayOfLong );
Arrays.stream( arrayOfLong ).limit( 10 ).forEach( i -> System.out.print( i + " " ) );
System.out.println();
//39 220 263 268 325 607 655 678 723 793
New JAVA Tools
• Nashorn engine: jjs
• Class dependency analyzer: jdeps
Nashorn engine: jjs
• jjs is a command line based standalone
Nashorn engine.
• It accepts a list of JavaScript source code files
as arguments and runs them.
Create a file func.js with following content:
function f() {
return “Hello ”;
};
print( f() + “World !” );
To execute this fie from command, let us pass it as an argument to jjs:
jjs func.js
The output on the console will be:
Hello World !
Class dependency analyzer: jdeps
• Provide a command-line tool in the JDK so that
developers can understand the static dependencies
of their applications and libraries.
jdeps org.springframework.core-3.0.5.RELEASE.jar
org.springframework.core-3.0.5.RELEASE.jar -> C:Program FilesJavajdk1.8.0jrelibrt.jar
org.springframework.core (org.springframework.core-3.0.5.RELEASE.jar)
-> java.io
-> java.lang
-> java.lang.annotation
-> java.lang.ref
-> java.lang.reflect
-> java.util
-> java.util.concurrent
-> org.apache.commons.logging not found
-> org.springframework.asm not found
-> org.springframework.asm.commons not found
org.springframework.core.annotation (org.springframework.core-3.0.5.RELEASE.jar)
-> java.lang
-> java.lang.annotation
-> java.lang.reflect
-> java.util
Java 9 Proposed Feature List
• Project Jigsaw – Modular Source Code
• Process API Updates
• Light Weight JSON API
• Money and Currency API
• Improved Contended Locking
• Segmented Code Cache
• Smart Java Compilation – Phase Two
Ad

More Related Content

What's hot (20)

Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
Mite Mitreski
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
Niraj Bharambe
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
Alok Kumar
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
Niraj Bharambe
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
BTI360
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
Tomasz Dziurko
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
Pramod Kumar
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
Alex Miller
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
tcurdt
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
David Gómez García
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
vito jeng
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
Jordi Gerona
 
Google Guava
Google GuavaGoogle Guava
Google Guava
Alexander Korotkikh
 
Java programs
Java programsJava programs
Java programs
Mukund Gandrakota
 
Java practical
Java practicalJava practical
Java practical
shweta-sharma99
 
Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?
tvaleev
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Sungchul Park
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
Ankur Gupta
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
Fiyaz Hasan
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
Mite Mitreski
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
Niraj Bharambe
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
Alok Kumar
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
BTI360
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
Tomasz Dziurko
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
Pramod Kumar
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
Alex Miller
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
tcurdt
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
David Gómez García
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
vito jeng
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
Jordi Gerona
 
Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?
tvaleev
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Sungchul Park
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
Ankur Gupta
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
Fiyaz Hasan
 

Viewers also liked (20)

Depilat crosshall glo 1
Depilat crosshall glo 1Depilat crosshall glo 1
Depilat crosshall glo 1
Globinvest Immobiliare
 
Rising Stars Holds Fundraising Golf Outing
Rising Stars Holds Fundraising Golf OutingRising Stars Holds Fundraising Golf Outing
Rising Stars Holds Fundraising Golf Outing
Paul Savramis
 
Vita first street preview glo
Vita first street preview gloVita first street preview glo
Vita first street preview glo
Globinvest Immobiliare
 
Rising Stars Partners with the YMCA to Help Youth Excel in School
Rising Stars Partners with the YMCA to Help Youth Excel in SchoolRising Stars Partners with the YMCA to Help Youth Excel in School
Rising Stars Partners with the YMCA to Help Youth Excel in School
Paul Savramis
 
Posizione vita first street
Posizione vita first streetPosizione vita first street
Posizione vita first street
Globinvest Immobiliare
 
Depliant idc inglese app
Depliant idc inglese appDepliant idc inglese app
Depliant idc inglese app
Globinvest Immobiliare
 
Rising Stars’ Meals from the Heart Program
Rising Stars’ Meals from the Heart ProgramRising Stars’ Meals from the Heart Program
Rising Stars’ Meals from the Heart Program
Paul Savramis
 
Crosshall planimetrie
Crosshall planimetrieCrosshall planimetrie
Crosshall planimetrie
Globinvest Immobiliare
 
δες την ζωη με μια αλλη ματια!
δες την ζωη με μια αλλη ματια!δες την ζωη με μια αλλη ματια!
δες την ζωη με μια αλλη ματια!
Maria Poulli
 
Vita Crosshall vista posizione
Vita Crosshall vista posizioneVita Crosshall vista posizione
Vita Crosshall vista posizione
Globinvest Immobiliare
 
Foto app vita first street
Foto app vita first streetFoto app vita first street
Foto app vita first street
Globinvest Immobiliare
 
Brochure glob vita first street
Brochure glob vita first streetBrochure glob vita first street
Brochure glob vita first street
Globinvest Immobiliare
 
Java8.part2
Java8.part2Java8.part2
Java8.part2
Ivan Ivanov
 
Daniel Steigerwald - Este.js - konec velkého Schizma
Daniel Steigerwald - Este.js - konec velkého SchizmaDaniel Steigerwald - Este.js - konec velkého Schizma
Daniel Steigerwald - Este.js - konec velkého Schizma
Develcz
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
Manav Prasad
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
Vadim Dubs
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
RichardWarburton
 
Rising Stars Holds Fundraising Golf Outing
Rising Stars Holds Fundraising Golf OutingRising Stars Holds Fundraising Golf Outing
Rising Stars Holds Fundraising Golf Outing
Paul Savramis
 
Rising Stars Partners with the YMCA to Help Youth Excel in School
Rising Stars Partners with the YMCA to Help Youth Excel in SchoolRising Stars Partners with the YMCA to Help Youth Excel in School
Rising Stars Partners with the YMCA to Help Youth Excel in School
Paul Savramis
 
Rising Stars’ Meals from the Heart Program
Rising Stars’ Meals from the Heart ProgramRising Stars’ Meals from the Heart Program
Rising Stars’ Meals from the Heart Program
Paul Savramis
 
δες την ζωη με μια αλλη ματια!
δες την ζωη με μια αλλη ματια!δες την ζωη με μια αλλη ματια!
δες την ζωη με μια αλλη ματια!
Maria Poulli
 
Daniel Steigerwald - Este.js - konec velkého Schizma
Daniel Steigerwald - Este.js - konec velkého SchizmaDaniel Steigerwald - Este.js - konec velkého Schizma
Daniel Steigerwald - Este.js - konec velkého Schizma
Develcz
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
Vadim Dubs
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
RichardWarburton
 
Ad

Similar to What is new in Java 8 (20)

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
Ganesh Samarthyam
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
KonfHubTechConferenc
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
Henri Tremblay
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
Alex Tumanoff
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
CodeOps Technologies LLP
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
Naresh Chintalcheru
 
Pattern Matching in Java 14
Pattern Matching in Java 14Pattern Matching in Java 14
Pattern Matching in Java 14
GlobalLogic Ukraine
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
Ganesh Samarthyam
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
Jussi Pohjolainen
 
Solr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene EuroconSolr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene Eurocon
Giovanni Fernandez-Kincade
 
Alternate JVM Languages
Alternate JVM LanguagesAlternate JVM Languages
Alternate JVM Languages
Saltmarch Media
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
Java
JavaJava
Java
박 경민
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
Ganesh Samarthyam
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
KonfHubTechConferenc
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
Henri Tremblay
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
CodeOps Technologies LLP
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
Naresh Chintalcheru
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
Ganesh Samarthyam
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
Ad

Recently uploaded (20)

Why Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card ProvidersWhy Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card Providers
Tapitag
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
AI in Business Software: Smarter Systems or Hidden Risks?
AI in Business Software: Smarter Systems or Hidden Risks?AI in Business Software: Smarter Systems or Hidden Risks?
AI in Business Software: Smarter Systems or Hidden Risks?
Amara Nielson
 
Adobe Media Encoder Crack FREE Download 2025
Adobe Media Encoder  Crack FREE Download 2025Adobe Media Encoder  Crack FREE Download 2025
Adobe Media Encoder Crack FREE Download 2025
zafranwaqar90
 
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdfProtect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
株式会社クライム
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Why Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card ProvidersWhy Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card Providers
Tapitag
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
AI in Business Software: Smarter Systems or Hidden Risks?
AI in Business Software: Smarter Systems or Hidden Risks?AI in Business Software: Smarter Systems or Hidden Risks?
AI in Business Software: Smarter Systems or Hidden Risks?
Amara Nielson
 
Adobe Media Encoder Crack FREE Download 2025
Adobe Media Encoder  Crack FREE Download 2025Adobe Media Encoder  Crack FREE Download 2025
Adobe Media Encoder Crack FREE Download 2025
zafranwaqar90
 
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdfProtect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
株式会社クライム
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 

What is new in Java 8

  • 1. What's New in JAVA 8 Sandeep Kumar Singh Solution Architect
  • 2. Agenda • New Features in Java language • New Features in Java libraries • New JAVA Tools
  • 3. New Features in Java language • Lambda expression • Method and Constructor References • Default Interface method • Repeating annotations • Improved Type Inference
  • 4. Lambda expression • Enable to treat functionality as a method argument, or code as data. • Lambda expressions express instances of single-method interfaces (referred to as functional interfaces) more compactly
  • 5. Examples List<String> strList = Arrays.asList("peter", "anna", "mike", "xenia"); for(String name : strList){ System.out.println(name); } Arrays.asList( "peter", "anna", "mike", "xenia" ).forEach( e -> System.out.println( e ) ); List<String> names = Arrays.asList("peter", "anna", "mike", "xenia"); Collections.sort(names, new Comparator<String>() { @Override public int compare(String a, String b) { return b.compareTo(a); } }); Collections.sort(names, (a, b) -> b.compareTo(a)); JAVA 7 JAVA 7 JAVA 8 JAVA 8
  • 6. Method and Constructor References • Provides the useful syntax to refer directly to exiting methods or constructors of Java classes or objects. • Java 8 enables you to pass references of methods or constructors via the :: keyword
  • 7. Examples (Method and Constructor References) class ComparisonProvider { public int compareByName(Person a, Person b) { return a.getName().compareTo(b.getName()); } public static int compareByAge(Person a, Person b) { return a.getBirthday().compareTo(b.getBirthday()); } } // Reference to an instance method ComparisonProvider myComparisonProvider = new ComparisonProvider(); Arrays.sort(rosterAsArray, myComparisonProvider::compareByName); // Reference to a static method Arrays.sort(rosterAsArray, ComparisonProvider ::compareByName); class Person { String firstName; String lastName; Person() {} Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } } interface PersonFactory<P extends Person> { P create(String firstName, String lastName); } PersonFactory<Person> personFactory = Person::new; Person person = personFactory.create("Peter", "Parker"); Method References Constructor References
  • 8. Default Interface method • Enable to add new functionality to an interface by utilizing the “default” keyword. • This is different from abstract methods as they do not have a method implementation • This ensures binary compatibility with code written for older versions of those interfaces.
  • 9. Examples (Default Interface method) interface Formula { double calculate(int a); default double sqrt(int a) { return Math.sqrt(a); } } Formula formula = new Formula() { @Override public double calculate(int a) { return sqrt(a * 10); } }; formula.calculate(10); // 10.0 formula.sqrt(4); //2
  • 10. Repeating annotations • Repeating Annotations provide the ability to apply the same annotation type more than once to the same declaration or type use. @Schedule(dayOfMonth="last") @Schedule(dayOfWeek="Fri", hour="23") public void doPeriodicCleanup() { ... } @Alert(role="Manager") @Alert(role="Administrator") public class UnauthorizedAccessException extends SecurityException { ... }
  • 11. Improved Type Inference • The Java compiler takes advantage of target typing to infer the type parameters of a generic method invocation. • The target type of an expression is the data type that the Java compiler expects depending on where the expression appears
  • 12. Examples (Improved Type Inference) class Value< T > { public static< T > T defaultValue() { return null; } public T getOrDefault( T value, T defaultValue ) { return ( value != null ) ? value : defaultValue; } } public class TypeInference { public static void main(String[] args) { final Value< String > value = new Value<>(); value.getOrDefault( "22", Value.<String>defaultValue() ); } } public class Value< T > { public static< T > T defaultValue() { return null; } public T getOrDefault( T value, T defaultValue ) { return ( value != null ) ? value : defaultValue; } } public class TypeInference { public static void main(String[] args) { final Value< String > value = new Value<>(); value.getOrDefault( "22", Value.defaultValue() ); } } JAVA 7 JAVA 8
  • 13. New Features in Java libraries • Optional • Streams • Date/Time API • Nashorn JavaScript engine • Base64 Encoder/Decoder • Parallel Arrays
  • 14. Optional (a solution to NullPointerExceptions) • Optional is a simple container for a value which may be null or non-null. • It provides a lot of useful methods so the explicit null checks have no excuse anymore. Example 1 :- Optional<String> optional = Optional.of("bam"); optional.isPresent(); // true optional.get(); // "bam" optional.orElse("fallback"); // "bam” optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b“ Example 2 :- Optional< String > fullName = Optional.ofNullable( null ); System.out.println( "Full Name is set? " + fullName.isPresent() ); //Full Name is set? false System.out.println( "Full Name: " + fullName.orElseGet( () -> "[none]" ) ); // Full Name: [none] System.out.println( fullName.map( s -> "Hey " + s + "!" ).orElse( "Hey Stranger!" ) ); //Hey Stranger!
  • 15. Streams • Stream API is integrated into the Collections API, which enables bulk operations on collections, such as sequential or parallel map- reduce transformations. int max = 1000000; List<String> values = new ArrayList<>(max); for (int i = 0; i < max; i++) { UUID uuid = UUID.randomUUID(); values.add(uuid.toString()); } Example 1 (Sequential Sort):- long count = values.stream().sorted().count(); System.out.println(count); // sequential sort took: 899 ms Example 2 (Parallel Sort) :- long count = values.parallelStream().sorted().count(); System.out.println(count); // parallel sort took: 472 ms
  • 16. Date/Time API • The Date-Time package, java.time, introduced in the Java SE 8 release • Provides a comprehensive model for date and time and was developed under JSR 310: Date and Time API. • Although java.time is based on the International Organization for Standardization (ISO) calendar system, commonly used global calendars are also supported.
  • 17. Examples (Date/Time API) Example1 (Clock) :- final Clock clock = Clock.systemUTC(); System.out.println( clock.instant() ); //2015-08-26T15:19:29.282Z System.out.println( clock.millis() ); //1397315969360 Example2 (Timezones) :- System.out.println(ZoneId.getAvailableZoneIds()); //prints all available timezone ids System.out.println(ZoneId.of("Europe/Berlin").getRules()); // ZoneRules[currentStandardOffset=+01:00] System.out.println(ZoneId.of("Brazil/East").getRules()); // ZoneRules[currentStandardOffset=-03:00] Example3 (LocalTime) :- LocalTime late = LocalTime.of(23, 59, 59); System.out.println(late); // 23:59:59 Example4 (LocalDate) :- LocalDate independenceDay = LocalDate.of(2015, Month.AUGUST, 15); DayOfWeek dayOfWeek = independenceDay.getDayOfWeek(); System.out.println(dayOfWeek); // SATURDAY Example5 (LocalDateTime) :- LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59); DayOfWeek dayOfWeek = sylvester.getDayOfWeek(); System.out.println(dayOfWeek); // WEDNESDAY
  • 18. Base64 Encoder/Decoder • Support of Base64 encoding has made its way into Java standard library with Java 8 release. final String text = "Base64 finally in Java 8!"; final String encoded = Base64.getEncoder() .encodeToString( text.getBytes( StandardCharsets.UTF_8 ) ); System.out.println( encoded ); // QmFzZTY0IGZpbmFsbHkgaW4gSmF2YSA4IQ== final String decoded = new String( Base64.getDecoder().decode( encoded ), StandardCharsets.UTF_8 ); System.out.println( decoded ); // Base64 finally in Java 8!
  • 19. Parallel Arrays • Java 8 release adds a lot of new methods to allow parallel arrays processing long[] arrayOfLong = new long [ 20000 ]; Arrays.parallelSetAll( arrayOfLong, index -> ThreadLocalRandom.current().nextInt( 1000000 ) ); Arrays.stream( arrayOfLong ).limit( 10 ).forEach( i -> System.out.print( i + " " ) ); System.out.println(); // 591217 891976 443951 424479 766825 351964 242997 642839 119108 552378 Arrays.parallelSort( arrayOfLong ); Arrays.stream( arrayOfLong ).limit( 10 ).forEach( i -> System.out.print( i + " " ) ); System.out.println(); //39 220 263 268 325 607 655 678 723 793
  • 20. New JAVA Tools • Nashorn engine: jjs • Class dependency analyzer: jdeps
  • 21. Nashorn engine: jjs • jjs is a command line based standalone Nashorn engine. • It accepts a list of JavaScript source code files as arguments and runs them. Create a file func.js with following content: function f() { return “Hello ”; }; print( f() + “World !” ); To execute this fie from command, let us pass it as an argument to jjs: jjs func.js The output on the console will be: Hello World !
  • 22. Class dependency analyzer: jdeps • Provide a command-line tool in the JDK so that developers can understand the static dependencies of their applications and libraries. jdeps org.springframework.core-3.0.5.RELEASE.jar org.springframework.core-3.0.5.RELEASE.jar -> C:Program FilesJavajdk1.8.0jrelibrt.jar org.springframework.core (org.springframework.core-3.0.5.RELEASE.jar) -> java.io -> java.lang -> java.lang.annotation -> java.lang.ref -> java.lang.reflect -> java.util -> java.util.concurrent -> org.apache.commons.logging not found -> org.springframework.asm not found -> org.springframework.asm.commons not found org.springframework.core.annotation (org.springframework.core-3.0.5.RELEASE.jar) -> java.lang -> java.lang.annotation -> java.lang.reflect -> java.util
  • 23. Java 9 Proposed Feature List • Project Jigsaw – Modular Source Code • Process API Updates • Light Weight JSON API • Money and Currency API • Improved Contended Locking • Segmented Code Cache • Smart Java Compilation – Phase Two
  翻译: