## Java8 contents 1.Lambda expressions 2. Functional interfaces 3. Painted method reference 4. The constructor reference | painted an array reference 5. Painted StreamAPI 6. Interface can define default methods and static methods ★ 7.Optional class introduced: to reduce null pointer exceptions 10. Using the Nashone engine to run JS on the JVM

##Java8 was introduced in 1995 with JDK1.0 and 2004 with JDK5 Reform is very big in 2006 launched JDK6, the longest version used in the enterprise ——– was acquired by Oralce company ———– 11 years launched JDK7 14 years launched JDK8 LTS version: Jdk11 LTS version launched in September 2018

Example 1: Interface A = Lambda expression;

Example 2: [mostly] method(Lambda expression); Public void method(interface A){} ### Example: (String o1, String O2)->{return o1.compareTo(o2); } Features: ① Parameter types in the left parameter list can be omitted! If there is only one argument in the left argument list, then the parentheses can be omitted. If there is only one argument in the left argument list, then the parentheses can be omitted. An interface that has only one abstract method is called a functional interface Consumer interface Supplier interface Function

functional interface Predicate interface
,r>

Method references are essentially a simplification of Lambda expressions, and can also be used as instances of functional interfaces. Methods that use method references must use Lambda expressions. Methods that use Lambda expressions may not use methods unless they meet the following requirements: ① There are only one sentence in the Lambda body ② the only sentence is a method call! ③ The argument list of the calling method is the same as that of the abstract method implemented by the Lambda body! The return type of the calling method is the same as that of the abstract method implemented by the Lambda body! Ordinary method call method caller is exactly the first parameter of abstract method, and other parameters consistent call method return type and abstract method return type consistent! Class name :: ordinary method * 2 class name :: static method * 3 Class name :: ordinary method * # summary of method references, array references, constructor references 1. Can use the method reference quote | | array constructor reference place, can certainly use Lambda expressions. 2. Use Lambda expressions, not necessarily can use the method reference quote | | array constructor reference, must meet the following condition 3. Where Lambda expressions can be used, anonymous inner classes must be able to use anonymous inner classes, not necessarily able to use Lambda expressions, must satisfy: the implementation of the interface is a functional interface (there is only one abstract method interface)! Method references: ① the Lambda body has only one sentence ② the only sentence is calling the method ③ the argument list and return type of the method exactly match the argument list and return type of the abstract method! Special: If it is a normal method with class name ::, the method caller is required to be the first argument of the abstract method, otherwise the same

This class is used to demonstrate method references * Examples: * Anonymous inner classes:  * UnaryOperator<Double> up = new UnaryOperator<Double>(){ * public Double apply(Double t){ * return Math.sqrt(t); * *}}; * Lambda: * UnaryOperator<Double> up =d-> math.sqrt (d); * Method reference: UnaryOperator<Double> up = Math:: SQRT; @test public void test1_1() {// Runnable r = new Runnable() {// @Override // public void run() { // System.out.println(); / / / /}}; // Method reference Runnable r2 = system.out ::println; r2.run(); Public void test1_2() {Consumer<String> con = new Consumer<String>() {// @override // public void accept(String t) { // System.out.println(t); // //} //}; // Method references Consumer<String> con2 = system. out::println; Con2. accept(" Zhao Liying and Feng Shaofeng have married "); } @test public void test2() {@test public void test2() {@test public void test2() int compare(Double o1, Double o2) { return Double.compare(o1, o2); }}; //Lambda Comparator<Double> com1 = (o1,o2)->Double.compare(o1, o2); <Double> com2 =Double::compare; @test public void test3() {Function<Employee,String> fun = new Function<Employee,String>(){ // @Override // public String apply(Employee t) { // return t.getName(); / / / /}}; Function<Employee,String> fun2 = Employee::getName; System.out.println(fun2.apply(new Employee("张 不 吉 ", 12, 1000, '男'))); } @test public void test3_2() {BiFunction<String, String, Boolean> bf = new BiFunction<String, String, Boolean>() { // @Override // public Boolean apply(String t, String u) { // return t.equals(u); / / / /}}; BiFunction<String, String, Boolean> bf2 = String::equals; System.out.println(bf2.apply("hello", "Hello")); }}Copy the code

Constructor reference

Understanding: A constructor reference is essentially a Lambda expression, but the statement is more concise. As an instance of a functional interface, usually passed to a method as a parameter! Where you can reference a constructor, you can definitely use a Lambda expression but where you can use a Lambda expression, you can’t necessarily reference a constructor

Call constructor new ClassName(argument list); call constructor new ClassName(argument list); The return type of an abstract method is the type of the constructor.

Syntax: Class name ::new

This class is used to demonstrate that the constructor references public Class TesttorRef {// Case 1: Return new String(); @test public void test1() {// Anonymous internal class // Supplier<String> sup = new Supplier<String>() {// @override // public String get() { // return new String(); / / / /}}; // Constructor references Supplier<String> sup2 = String::new; int length = sup2.get().length(); System.out.println(length); } // Case 2: Return new StringBuffer(int capacity); @Test public void test2() { Function<Integer,StringBuffer> fun = new Function<Integer,StringBuffer>(){ @Override public StringBuffer apply(Integer t) { return new StringBuffer(t); }}; Function<Integer,StringBuffer> fun2 = StringBuffer::new; } // Case 3: Return new Employee(" duan Yu ", 22, 10000, 'male') @ Test public void test3 () {A < String, Integer, Double, Character, the Employee > a1 = (s, I, d, c) - > new Employee (s, I, d, c); A<String,Integer,Double,Character,Employee> a = Employee::new; } } interface A<T,R,U,M,N>{ N test(T t,R r,U u,M m); }Copy the code

Understanding array references: Array references are essentially Lambda expressions, but with more concise statements. As an instance of a functional interface, usually passed to a method as a parameter!

Where arrays can be referenced, they must be referenced by Lambda expressions. Where arrays can be referenced by Lambda expressions, they must not be referenced by arrays. ③ The abstract method takes only one parameter, the length of the array. The abstract method returns the syntax for the new array type created: array type []::new

Public class TestArrayRef {// Return String[] s = new String[5] @test public void test1() {// Function<Integer,String[]> fun = new Function<Integer,String[]>(){ // @Override // public String[] apply(Integer t) { // return new String[t]; / / / /}}; Function<Integer,String[]> fun2 = String[]::new; String[] arr = fun2.apply(5); for (String string : arr) { System.out.println(string); Public void test2() {Function<Integer,Employee[]> fun = Employee[]::new; Employee[] apply = fun.apply(3); for (Employee employee : apply) { System.out.println(employee); }}}Copy the code

Review: an anonymous inner class Lambda expressions, method reference quote | | array constructor references

##StreamAPI

Benefits 1, more efficient 2, easy to use, provides a rich and powerful method.

Create a Stream object that points to a specific data source (collection, array, set of values, wireless Stream) 2. Intermediate operations (optional 0 to n) : Calculate and process data from the data source 3. Abort operation (√) Description: Want a result (print, count, deminimize, etc.)

### Use features

A Stream can only be consumed once, and once consumed, it cannot be used again. A Stream can only be consumed once, and cannot be used again. Unless a Stream object is recreated, there can be zero or more intermediate operations on a Stream, and each operation returns a new Stream. 5. Stream is a more powerful Iterator that can handle more complex data and is more efficient in parallelization.Copy the code

★ Stream = list.stream(); Stream = array.stream (Array); Stream Stream = stream.of (T… Stream = Stream. Generate (Supplier sup);

/** * This class is used to demonstrate the use of a Stream. 1. Create a Stream object that points to the data source. 2. Create a Stream from a collection object. Create a Stream from an array object. Create a Stream from an array object. @test public void test1() {List<Employee> List = employeedata.getData (); Stream<Employee> stream = list.stream(); ParallelStream = list.parallelstream (); // Stream<Employee> parallelStream = list.parallelstream (); Stream.foreach (system.out ::println); array@test public void test2() {Stream<String> Stream = array.stream (new String[]) {" white eagle King "," Green axe King "," Purple Dragon King "," Golden Lion King "}); stream.forEach(System.out::println); } // 3, create Stream @test public void test3() {Stream<String> of = stream.of (" "," "," "," "); of.forEach(System.out::println); } @test public void test4() {Stream<Double> Stream = Stream. Generate (Math::random); stream.forEach(System.out::println); @test public void exec1() {// employeedata.getData ().stream().foreach (system.out ::println); Person p = new Person(); // p.eat(); // p.sleep(); // p.play(); // p.study(); p.eat().sleep().play().study(); }} class Person{public Person eat() {system.out.println (" eat "); return this; } public Person sleep() {system.out.println (" sleep "); return this; } public Person play() {system.out.println (" play "); return this; } public Person study() {system.out.println (" learn "); return this; }}Copy the code

* filter(Predicate): filters elements based on conditions * limit(long Max): extracts elements whose size<= Max * Skip (long s): skips the first s * DISTINCT (): returns a set of distinct elements, Determine duplicates based on hashCode and equals * map(Function): maps to new elements * flatMap(Function): maps to new elements of Stream type * sorted(): naturally sorted * Sorted (Comparator): Custom sort *

/** * This class is used to demonstrate the use of Stream step 2: Each intermediate operation returns a new Stream that holds the result. The intermediate operation is a lazy evaluation and must wait to terminate the operation before processing the result. Unless a new Stream * ④ intermediate operation is recreated to implement chain calls! * Common methods: * Filter (Predicate) : * distinct(): delete * map(Function): map * flatMap(Function): map, return Stream * sorted(): natural sort, */ public class TestStreamMiddle {List<Employee> List; @Before public void before() { list = EmployeeData.getData(); } /* * Filter and slice * filter(Predicate P) -- receives Lambda, excludes certain elements from the stream. Limit (n) -- Truncates the stream so that it does not exceed a given number of elements. Skip (n) -- Skip the element, returning a stream with the first n elements thrown away. If there are less than n elements in the stream, an empty stream is returned. */ @test public void test1() {//1 */ @test public void test1() { Stream<Employee> Stream = list.stream(); // Stream<Employee> filter = stream.filter(t->t. gegender ()==' male '); // Stream<Employee> limit = stream.limit(5); Stream<Employee> skip = stream.skip(3); Stream<Employee> skip = stream.skip(3); // Method 4: Stream<Employee> distinct = stream.distinct() : Distinct () : two elements are repeated by their equals () methods if they return true. ForEach (system.out ::println); //3. } /** * mapping * map: mapping (elements to any type) */ @test public void test2() {//1. Stream<Employee> Stream = list.stream(); Stream<String> map = stream.map(Employee::getName); Stream<String> map = stream.map(Employee::getName); // Stream<String> filter = map.filter(s-> s.taines (" segment ")); Stream<Stream<Object>> map = stream.map(TestStreamMiddle::fromEmployeeToStream); / / method 6: flatMap / / Stream < Object > flatMap = Stream. FlatMap (TestStreamMiddle: : fromEmployeeToStream); Filter.foreach (system.out ::println); map.forEach(System.out::println); } /* * Sorted * sorted() -- sorted by nature (Comparator com) -- sorted by custom */ @test public void test3() {//1. Stream<Employee> Stream = list.stream(); Sorted = stream.sorted(); // Stream<Employee> sorted = stream.sorted(); // Method 8: Sorted (Comparator) Stream<Employee> sorted = stream.sorted((o1,o2)->Double.compare(o2.getsalary (), o1.getSalary())); ForEach (system.out ::println); Public static Stream<Object> fromEmployeeToStream(Employee e){return Stream.of(e.getName(),e.getAge(),e.getGender(),e.getSalary()); } // Example: Get salary >6000, item 2 -- item 8 data, and remove duplicates, @test public void exec1() {employeeData.getData ().stream ().filter (t-> t.get_salary ()>6000).skip (1).limit (7). distinct(). forEach(System.out::println); } // Exercise 1: Get the name of an employee whose name length is greater than 2. @Test public void exec2() { list.stream().map(Employee::getName).filter(s->s.length()>2).forEach(System.out::println); } // Exercise 2: @test public void exec3() {public void exec3() { list.stream().filter(e->e.getAge()<30&&e.getSalary()>5000).map(Employee::getSalary).forEach(System.out::println); } // Exercise 3: @test public void exec4() { list.stream().sorted((e1,e2)->Integer.compare(e2.getAge(),e1.getAge())).limit(3).map(Employee::getSalary).forEach(System .out::println); }}Copy the code

* allMatch: tests whether all matches * anyMatch: tests whether at least one matches * noneMatch: tests whether all matches * findFirst: Return the first * findAny: returns any of the parallel streams * count: number of statistics * Max (comparator): returns the maximum value * min(comparator): returns the minimum value * forEach(Consumer): internal iteration (traversal) * Reduce (BinaryOperator): reduced, often used together with map

/** * this class is used to demonstrate the use of Stream step 3: Terminate operation * common methods: * reduce: Reduction ★ * forEach: internal iteration ★ * Max: Calculates the maximum value * min: calculates the minimum value * count: calculates the number of statistics ★ * allMatch: checks whether all elements match the specified condition * anyMatch: checks whether at least one element matches the specified condition * NoneMatch: checks if all elements do not match the specified condition * findFirst: returns the first element * findAny: returns any element * collect: converts Stream to a collection object */ public class TestStreamEnd  { List<Employee> list; @Before public void before() { list = EmployeeData.getData(); } /** * matches and finds * allMatch(Predicate P) -- checks for all elements anyMatch(Predicate P) -- checks for at least one element noneMatch(Predicate P) FindFirst -- returns the first element -- returns any element in the current stream */ @test public void test1() {//1. Stream<Employee> Stream = list.stream(); Boolean allMatch = stream.anymatch (e-> LLDB salary ()>10000); System.out.println(allMatch); } /* * count * Max * min * forEach */ @test public void test2() {//1 Stream<Employee> Stream = list.stream(); Long count = stream.count(); long count = stream.count(); // System.out.println(count); Optional<Employee> Max = stream.max((o1, O2)-> o1.getage () -o2.getage ()); System.out.println(max); */ @test public void test3() {//1. Stream<Employee> Stream = list.stream(); Sum = stream.map(Employee:: salary).reduce((t,u)->t+u); System.out.println(sum); } /* * collect: collect */ @test public void test4() {//1. Stream<Employee> Stream = list.stream(); List<Employee> collect = stream.collect(Collectors. ToList ()); //2. System.out.println(collect); } // Exercise 2: Number of employees whose names contain horses @test public void exec2() {Optional<Integer> reduce = List. The stream (). The filter (t - > t.g etName (). The contains (" horse "). The map (t - > 1). The reduce ((t, u) - > t + u). System.out.println(reduce); } // Exercise: return the highest salary:  @Test public void exec1() { Optional<Double> max = list.stream().map(Employee::getSalary).max(Double::compare); System.out.println(max); }}Copy the code

Static methods and default methods are allowed in the interface syntax:

Static method: public static method name (parameter list) {} Default method: public default Method name (parameter list) {}Copy the code

Use features: 1, static methods can not be implemented class or subinterface inheritance, can only be called by the name of the interface! 2. Default methods have inheritance. Can be inherited by an implementation class or subinterface

Solve the conflict with the same problem: 1, the principle of class When the parent class and/or in the implementation of the interface and has the same name to achieve good method, if the subclasses without rewriting, the default is the parent class method 2, when implement multiple interfaces in the same name and have achieved good method, subclasses must override this method, otherwise an error! JDK9: Description: Private methods are allowed in the interface

Grammar:

Private Return type method name (argument list){// code}Copy the code

Optional is essentially a container that wraps objects of a specific type. The null pointer exception can be avoided

Methods:

of
ofNullable
orElse
Copy the code

Jdk8 supports repeated annotation syntax: above modified data: @ annotation class name @ annotation class name…

Example:

public class TestJava8Ann { @MyAnn @MyAnn // @AnnArray({@MyAnn,@MyAnn}) String name; } @repeatable (annarray.class) @interface MyAnn{// syntax: type value() [default]; } @interface AnnArray{ MyAnn[] value(); }Copy the code

Date of # # API

First generation Date: Date class SimpleDateFormat class

Date date = new Date(); SimpleDateFormat SDF = new SimpleDateFormat(" YYYY-MM-DD hh:: MM ::ss"); String dateString = sdf.format(date);Copy the code
/** * new Date(); /** new Date(); * SimpleDateFormat * format * parse */ public class TestDate1 { @test public void test1() {Date d1 = new Date(); System.out.println(d1); System.out.println(d1.getTime()); // Get the number of milliseconds from 1970-1-1. @test public void test2() throws ParseException {Date d=new Date(); 18 8-8 4:25 PM // SimpleDateFormat SDF = new SimpleDateFormat(); SimpleDateFormat SDF = new SimpleDateFormat(" YYYY yyyy MM MM dd hh hh MM min ss SEC S ms "); / / -- -- -- -- -- -- -- -- -- -- -- -- -- the formatted date (to convert the date to String) -- -- -- -- -- -- -- -- -- -- -- -- a String format = SDF. The format (d); System.out.println(format); / / -- -- -- -- -- -- -- -- -- -- -- -- parse the String for the date (to convert a String to date) -- -- -- -- -- -- -- -- the String s = "December 12, 2018, 12 hours 12 minutes 12 millisecond 12 seconds". Date date = sdf.parse(s); System.out.println(date); }}Copy the code

The second generation of dates: Calendar Abstract classes: Focus more on getting and setting Calendar fields

Calendar date = Calendar.getInstance(); System.out.println(date); int year = date.get(Calendar.YEAR); int month = date.get(Calendar.MONTH); int day = date.get(Calendar.DAY_OF_MONTH); System. Out. Println (" year "+ year + (the month + 1) +" month "+ day +", ");Copy the code
Public class TestDate2 {@test public void test1() {//1. Calendar c = calendar.getInstance (); // System.out.println(c); System.out.println(" YEAR: "+ c.net (calendar.year)); System. The out. Println (" : "+ be sad et (Calendar. The MONTH) chtistina georgina rossetti.british poetess (+ 1)); System. The out. Println (" : "be sad et chtistina georgina rossetti.british poetess + (Calendar. DAY_OF_MONTH)); System.out.println(" HOUR: "+ c.net (calendar.hour)); System.out.println(" min: "+ c.net (calendar.minute)); System. The out. Println (" seconds: "be sad et chtistina georgina rossetti.british poetess + (Calendar. SECOND)); System.out.println("------------------------------------------"); C. set(2000, 1, 1); System. The out. Println (" : "be sad et chtistina georgina rossetti.british poetess + (Calendar. YEAR)); System. The out. Println (" : "+ be sad et (Calendar. The MONTH) chtistina georgina rossetti.british poetess (+ 1)); System. The out. Println (" : "be sad et chtistina georgina rossetti.british poetess + (Calendar. DAY_OF_MONTH)); System.out.println(" HOUR: "+ c.net (calendar.hour)); System.out.println(" min: "+ c.net (calendar.minute)); System. The out. Println (" seconds: "be sad et chtistina georgina rossetti.british poetess + (Calendar. SECOND)); }}Copy the code

Third Generation Date:

/ / 1. LocalDate/LocalTime/LocalDateTime -- -- - > Calendar @ Test public void test1 () {/ / (1) create a date object LocalDateTime LDT = LocalDateTime.now(); //System.out.println(ldt); Int year = ldt.getYear(); int month = ldt.getMonthValue(); int day = ldt.getDayOfMonth(); int hour = ldt.getHour(); int minute = ldt.getMinute(); int second = ldt.getSecond(); System. Out. Println (" year "+ year + month + + day" month "+", "+ hour + + minute" hour "+" minutes "+ second +" seconds "); } //2.Instant————————> date@test public void test2() { //Instant——————>Date Date Date = Date. From (now); System.out.println(date); //Date——————>Instant Instant = date.toinstant (); System.out.println(instant); } //3.DateTimeFormatter——————>SimpleDateFormat /* * Can format LocalDateTime, @test public void test3() {LocalDateTime LDT = localDatetime.now (); / / (1) create DateTimeFormatter object DateTimeFormatter DTF = DateTimeFormatter. OfPattern (" yyyy - MM - dd kk: : MM: : ss "); Format (date ——————> String) String format = dtf.format(LDT); System.out.println(format); //③ LocalDateTime parse = LocalDateTime. Parse ("2018-08-08 16::32::21", DTF); System.out.println(parse); }Copy the code