© Luxoft Training 2013 Java 8 New language features.

Презентация:



Advertisements
Похожие презентации
Unit II Constructor Cont… Destructor Default constructor.
Advertisements

© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
1/30 Chapter 8: Dynamic Binding And Abstract classes.
© Luxoft Training 2013 Java Collections API. © Luxoft Training 2013 Collections hierarchy.
1 © Luxoft Training 2012 Inner and anonymous classes.
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
1/27 Chapter 9: Template Functions And Template Classes.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Interface.
© Luxoft Training 2013 Using Reflection API in Java.
A class is just a collection of variables--often of different types--combined with a set of related functions. The variables in the class are referred.
Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
Java Collections Framework (JCF) in Java Tutorial for students of universities Author: Oxana Dudnik.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Polymorphism.
Operators and Arithmetic Operations. Operators An operator is a symbol that instructs the code to perform some operations or actions on one or more operands.
Data Types in C. A Data Type A data type is –A set of values AND –A set of operations on those values A data type is used to –Identify the type of a variable.
Учимся писать Эссе. Opinion essays § 1- introduce the subject and state your opinion § 2-4 – or more paragraphs - first viewpoint supported by reasons/
Initialization & Cleanup Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
Object-Oriented Programming Ramzi Saifan Program Control Slides adapted from Steven Roehrig.
© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
Транксрипт:

© Luxoft Training 2013 Java 8 New language features

2 © Luxoft Training 2012 List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); for (int number : numbers) { System.out.println(number); } numbers.forEach((Integer value) -> System.out.println(value)); numbers.forEach(value -> System.out.println(value)); numbers.forEach(System.out::println); Lambda expressions

3 © Luxoft Training 2012 class Student { String name; int gradYear; double score; } Collection students =...; Lambda expressions

4 © Luxoft Training 2012 Collection students =...; double max = Double.MIN_VALUE; for (Student s : students) { if (s.gradYear == 2011) max = Math.max(max, s.score); } Lambda expressions

5 © Luxoft Training 2012 Collection students =...; max = students.filter(new Predicate () { public boolean op(Student s) { return s.gradYear == 2010; } }).map(new Extractor () { public Double extract(Student s) { return s.score; } }).reduce(0.0, new Reducer () { public Double reduce(Double max, Double score) { return Math.max(max, score); } }); Lambda expressions

6 © Luxoft Training 2012 Inner Classes Are Imperfect Closures Bulky syntax Unable to capture non-final local variables Transparency issues Meaning of return, break, continue, this No non-local control flow operators

7 © Luxoft Training 2012 Single Abstract Method (SAM) Types Lots of examples in the Java APIs Runnable, Callable, EventHandler, Comparator Noise:Work ratio is 5:1 Lambda expressions grow out of the idea of making callback objects easier foo.doSomething(new CallbackHandler() { public void callback(Context c) { System.out.println(c.v()); } });

8 © Luxoft Training 2012 Collection students =...; max = students.filter((Student s) -> s.gradYear == 2011).map((Student s) -> s.score).reduce(0.0, (Double max, Double score) -> Math.max(max, score)); max = students.filter(s -> s.gradYear == 2011).map(s -> s.score).reduce(0.0, Math::max); max = students.parallel().filter(s -> s.gradYear == 2011).map(s -> s.score).reduce(0.0, Math::max); Lambda expressions

9 © Luxoft Training 2012 Method references public class Person { public enum Sex { MALE, FEMALE } String name; Date birthday; Sex gender; String Address; public static int compareByAge(Person a, Person b) { return a.birthday.compareTo(b.birthday); } Person[] rosterAsArray = roster.toArray(new Person[roster.size()]); class PersonAgeComparator implements Comparator { public int compare(Person a, Person b) { return a.getBirthday().compareTo(b.getBirthday()); } Arrays.sort(rosterAsArray, new PersonAgeComparator());

10 © Luxoft Training 2012 Method references Arrays.sort(rosterAsArray, (Person a, Person b) -> { return a.getBirthday().compareTo(b.getBirthday()); } ); However, this method to compare the birth dates of two Person instances already exists as Person.compareByAge. You can invoke this method instead in the body of the lambda expression: Arrays.sort(rosterAsArray, (a, b) -> Person.compareByAge(a, b) ); Because this lambda expression invokes an existing method, you can use a method reference instead of a lambda expression: Arrays.sort(rosterAsArray, Person::compareByAge);

11 © Luxoft Training 2012 Method references Arrays.sort(rosterAsArray, Person::compareByAge); The method reference Person::compareByAge is semantically the same as the lambda expression (a, b) -> Person.compareByAge(a, b). Each has the following characteristics: Its formal parameter list is copied from Comparator.compare, which is (Person, Person). Its body calls the method Person.compareByAge.

12 © Luxoft Training 2012 Reference to an Instance Method of an Arbitrary Object of a Particular Type String[] stringArray = { "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" }; Arrays.sort(stringArray, String::compareToIgnoreCase); The equivalent lambda expression for the method reference String::compareToIgnoreCase would have the formal parameter list (String a, String b), where a and b are arbitrary names used to better describe this example. The method reference would invoke the method a.compareToIgnoreCase(b).

13 © Luxoft Training 2012 public static, DEST extends Collection > DEST transferElements(SOURCE sourceCollection, Supplier collectionFactory) { DEST result = collectionFactory.get(); for (T t : sourceCollection) { result.add(t); } return result; } The functional interface Supplier contains one method get that takes no arguments and returns an object. Consequently, you can invoke the method transferElements with a lambda expression as follows: Set rosterSetLambda = transferElements(roster, () -> { return new HashSet<>(); }); You can use a constructor reference in place of the lambda expression as follows: Set rosterSet = transferElements(roster, HashSet::new); The Java compiler infers that you want to create a HashSet collection that contains elements of type Person. Alternatively, you can specify this as follows: Set rosterSet = transferElements(roster, HashSet ::new); Reference to a constructor

14 © Luxoft Training 2012 Function: takes a value, returns a value Static method references are probably the easiest to understand. For example, the method Integer.valueOf(String) can be converted into a Function. Intuitively, thats exactly what it is already - a context-less method that takes a String and returns an Integer.

15 © Luxoft Training 2012 Function: define your own function public class LambdaTest { public String process(String s, Function f) { return f.apply(s); } public String addExclam(String s) { return s+"!"; } public static void main(String[] args) { LambdaTest lambdaTest = new LambdaTest(); String s = lambdaTest.process("hello", lambdaTest::addExclam); System.out.println(s); System.out.println( lambdaTest.process("hello", x->x+"?")); } hello! hello?

16 © Luxoft Training 2012 Supplier: returns single value Instance-capturing method references are, as the name implies, a way to capture instances in the enclosing type. Consider Integer.toString, which converts an integer instance back into a String:

17 © Luxoft Training 2012 BiFunction: takes 2 parameters, returns a value Interface BiFunction Type Parameters: T - the type of the first argument to the function U - the type of the second argument to the function R - the type of the result of the function This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

18 © Luxoft Training 2012 reduce() Interface BinaryOperator T - the type of the operands and result of the operator All Superinterfaces: BiFunction This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value. This is equivalent to: but is not constrained to execute sequentially. The identity value must be an identity for the accumulator function. This means that for all t, accumulator.apply(identity, t) is equal to t. The accumulator function must be an associative function. This is a terminal operation.

19 © Luxoft Training 2012 Default methods public interface TimeClient { void setTime(int hour, int minute, int second); void setDate(int day, int month, int year); void setDateAndTime(int day, int month, int year, int hour, int minute, int second); LocalDateTime getLocalDateTime(); ZonedDateTime getZonedDateTime(String zoneString); } public class SimpleTimeClient implements TimeClient {... } Following this modification to the TimeClient interface, you would also have to modify the class SimpleTimeClient and implement the method getZonedDateTime. You can instead define a default implementation.

20 © Luxoft Training 2012 public interface TimeClient { void setTime(int hour, int minute, int second); void setDate(int day, int month, int year); void setDateAndTime(int day, int month, int year, int hour, int minute, int second); LocalDateTime getLocalDateTime(); static ZoneId getZoneId (String zoneString) { try { return ZoneId.of(zoneString); } catch (DateTimeException e) { System.err.println("Invalid time zone: " + zoneString); return ZoneId.systemDefault(); } default ZonedDateTime getZonedDateTime(String zoneString) { return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString)); } Default methods