SlideShare une entreprise Scribd logo
1  sur  23
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

Contenu connexe

Tendances

Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iiiNiraj 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 WorldBTI360
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya 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 knowTomasz Dziurko
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex 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 wheeltcurdt
 
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 Developmentvito 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 & AndroidJordi 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 101Ankur Gupta
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6Fiyaz Hasan
 

Tendances (20)

Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
 
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
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
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
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
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
 
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.
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
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
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Java programs
Java programsJava programs
Java programs
 
Java practical
Java practicalJava practical
Java practical
 
Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 

En vedette

Rising Stars Holds Fundraising Golf Outing
Rising Stars Holds Fundraising Golf OutingRising Stars Holds Fundraising Golf Outing
Rising Stars Holds Fundraising Golf OutingPaul 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 SchoolPaul 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 ProgramPaul 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 SchizmaDevelcz
 
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 8RichardWarburton
 

En vedette (20)

Depilat crosshall glo 1
Depilat crosshall glo 1Depilat crosshall glo 1
Depilat crosshall glo 1
 
Rising Stars Holds Fundraising Golf Outing
Rising Stars Holds Fundraising Golf OutingRising Stars Holds Fundraising Golf Outing
Rising Stars Holds Fundraising Golf Outing
 
Un prezioso consiglio fv
Un prezioso consiglio fvUn prezioso consiglio fv
Un prezioso consiglio fv
 
Vita first street preview glo
Vita first street preview gloVita first street preview glo
Vita first street preview glo
 
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
 
Posizione vita first street
Posizione vita first streetPosizione vita first street
Posizione vita first street
 
Brochure ita idc verdiani f
Brochure ita idc verdiani fBrochure ita idc verdiani f
Brochure ita idc verdiani f
 
Depliant idc inglese app
Depliant idc inglese appDepliant idc inglese app
Depliant idc inglese app
 
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
 
Crosshall planimetrie
Crosshall planimetrieCrosshall planimetrie
Crosshall planimetrie
 
δες την ζωη με μια αλλη ματια!
δες την ζωη με μια αλλη ματια!δες την ζωη με μια αλλη ματια!
δες την ζωη με μια αλλη ματια!
 
Vita Crosshall vista posizione
Vita Crosshall vista posizioneVita Crosshall vista posizione
Vita Crosshall vista posizione
 
Foto app vita first street
Foto app vita first streetFoto app vita first street
Foto app vita first street
 
Nozioni di base sul diamante
Nozioni di base sul diamanteNozioni di base sul diamante
Nozioni di base sul diamante
 
Brochure glob vita first street
Brochure glob vita first streetBrochure glob vita first street
Brochure glob vita first street
 
Java8.part2
Java8.part2Java8.part2
Java8.part2
 
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
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 

Similaire à What is new in Java 8

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 8Ganesh 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 programmingHenri Tremblay
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancementRakesh 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 StreamsCodeOps Technologies LLP
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code ExamplesNaresh 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 fundamentalsHCMUTE
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin 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 beyondMario Fusco
 

Similaire à What is new in Java 8 (20)

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
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
 
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)
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
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
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
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
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
Pattern Matching in Java 14
Pattern Matching in Java 14Pattern Matching in Java 14
Pattern Matching in Java 14
 
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
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
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?
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Solr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene EuroconSolr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene Eurocon
 
Alternate JVM Languages
Alternate JVM LanguagesAlternate JVM Languages
Alternate JVM Languages
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
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
 
Java
JavaJava
Java
 

Dernier

MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 

Dernier (20)

MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 

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