Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java 8 new features

196 views

Published on

New features and enhancements added in Java 8.

Published in: Education
  • Be the first to comment

  • Be the first to like this

Java 8 new features

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

×