what is new in java 8
TRANSCRIPT
What's New in JAVA 8
Sandeep Kumar SinghSolution 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.0formula.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(); // trueoptional.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.282ZSystem.out.println( clock.millis() ); //1397315969360
Example2 (Timezones) :- System.out.println(ZoneId.getAvailableZoneIds()); //prints all available timezone idsSystem.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 Files\Java\jdk1.8.0\jre\lib\rt.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