preface

Jdk8 adds a lot of things, which can be broken down into the following categories (Lambda expressions and Stream APIS are highlighted here)

  • Lambda expressions
  • Functional interface
  • Method references and constructor calls
  • Stream API
  • Default and static methods in the interface
  • New date and time API

A, Stream Api

1. Stream features

① The Stream does not store elements by itself. ②Stream does not change the source object. Instead, they return a new Stream holding the result. ③ The Stream operation is delayed. This means they wait until they need results

2. Execution process

2.1 Stream instantiation

2.2 a series of intermediate operations (filtering, mapping,…)

An intermediate chain of operations that processes data from the data source

3. Terminate the operation

Once the termination operation is performed, the intermediate operation chain is executed and the result is produced. After that, it won’t be used again. Once it’s over, to use it again, you have to reinvent it. Intermediate operations are performed only if there is a termination operation.

4. Creation method

// Default Stream Stream () : return a sequential Stream Stream = employees.stream(); //employees is a collection

ParallelStream = employees.parallelstream ();

Int [] arr = new int[]{1,2,3,4,5,6}; // Array static Stream Stream (T[] array): Returns a Stream IntStream = array.stream (arr); // Return type I IntStream

Employee e1 = new Employee(1001, “Tom”); Employee e2 = new Employee(1002, “Jerry”); Employee[] arr1 = new Employee[]{e1,e2}; Stream stream1 = Arrays.stream(arr1);

Of () Stream = stream.of (1, 2, 3, 4, 5, 6);

// Create a Stream

// Iterate // public static Stream iterate(final T seed, final UnaryOperator f) // Iterate: Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println); //limit terminates the operation and outputs only 10 values

Public static Stream generate(Supplier s) Stream. Generate (Math::random).limit(10).foreach (system.out ::println); // Outputs 10 random numbers

5. Actual combat records

Personally feel that every knowledge point to learn, or only more actual combat to learn better

public class EmployeeData { public static List<Employee> getEmployees(){ List<Employee> list = new ArrayList<>(); List. add(new Employee(1001, "Ma huateng ", 34, 6000.38)); List. add(new Employee(1002, "jack ", 12, 9876.12)); List. add(new Employee(1003, "Liu Qiongdong ", 33, 3000.82)); List.add (new Employee(1004, "lei ", 26, 7657.37)); list.add(new Employee(1004," Lei ", 26, 7657.37)); List. add(new Employee(1005, "Robin Li ", 65, 5555.32)); List.add (new Employee(1006, "Bill Gates ", 42, 9500.43)); List. add(new Employee(1007, "Ren Zhengfei1 ", 26, 4333.32)); List.add (new Employee(1008, "Zuckerberg ", 35, 2500.32)); return list; }} List<Employee> list = EmployeeData.getEmployees(); // Filter (Predicate P) - Receives Lambda, excludes certain elements from the stream. Stream<Employee> stream = list.stream(); Stream.filter (e -> LLDB salary () > 7000).foreach (system.out ::println); System.out.println(); // skip(n) -- Skip the element and return a stream with the first n elements thrown away. If there are less than n elements in the stream, an empty stream is returned. List.stream ().skip(3).foreach (system.out ::println); System.out.println(); // Skip system.out.println (); // distinct() -- filter to remove duplicate elements from list.add(new Employee(1010," liu qiangeast ",40,8000)) by hashCode() and equals() of the elements generated by the stream; List.add (new Employee(1010," liu qiongdong ",41,8000)); List. add(new Employee(1010," liu qiangdong ",40,8000)); List. add(new Employee(1010," liu qiangdong ",40,8000)); List. add(new Employee(1010," liu qiangdong ",40,8000)); // System.out.println(list); list.stream().distinct().forEach(System.out::println);Copy the code

Mapping:

// map(Function f) -- Takes a Function as an argument to convert elements to other forms or extract information. This Function is applied to each element and maps it to a new element. List<String> list = Arrays.asList("aa", "bb", "cc", "dd"); list.stream().map(str -> str.toUpperCase()).forEach(System.out::println); // Map retrieves each element in the list, automatically iterates over each element, uppercase each element, and returns a STRCopy the code

The sorting

3- sorted @test public void test4(){// Sorted () -- naturally sorted List<Integer> List = array.aslist (12, 43, 65, 34, 87, 0, -98, 7); list.stream().sorted().forEach(System.out::println); / / throw exceptions, reason: the Employee does not implement the Comparable interface / / the List < Employee > employees = EmployeeData. The getEmployees (); // employees.stream().sorted().forEach(System.out::println); / / sorted (Comparator com) - custom sorting List < Employee > employees = EmployeeData. The getEmployees (); employees.stream().sorted( (e1,e2) -> { int ageValue = Integer.compare(e1.getAge(),e2.getAge()); if(ageValue ! = 0){ return ageValue; }else{ return -Double.compare(e1.getSalary(),e2.getSalary()); } }).forEach(System.out::println); }Copy the code

Lambda expressions

1、为什么使用Lambda

  • In Java, we can’t pass a function as an argument to a method, declare a method that returns a function, or declare a method that returns a function,
  • In JavaScript, it is quite common for a function argument to be one function and a return value to be another function; JavaScript is a very typical functional language.

2. What Lambda expressions do

  • Lambda expressions add missing functional programming features to Java, allowing us to treat functions as first-class citizens
  • In languages that treat functions as first-class citizens, Lambda expressions are of type functions. But in Java, Lambda expressions are objects, and they must be attached to a special class of object types — > Functional Interface.

3. Anonymous inner class (example)

3.1. Previous writing

public static void main(String[] args) { Thread thread = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(i); }}}); }Copy the code

3.2. Use Lambda expressions

public static void main(String[] args) { new Thread(()->{ for (int i = 0; i < 100; i++) { System.out.println(i); }}); }Copy the code

4. Lambda expression format

4.1, introduction to

(Parameter list) -> {} (parameter list) : parameter list, optional {}: square body ->: no actual connectionCopy the code

4.2. No parameter No return value

@FunctionalInterface interface MyInterFace1 { void test1(); } public class Test2 { public static void main(String[] args) { fun1(()->{ System. The out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- method performs the -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "); }); } public static void fun1(MyInterFace1 myInterFace) { myInterFace.test1(); }}Copy the code

4.3 No return value for a parameter

@FunctionalInterface interface MyInterFace { void test1(String name); } public class Test2 {public static void main(String[] args) { Just write code looks more comfortable fun1 ((String name) - > {System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- method performs the -- -- -- -- -- -- -- -- -- -- "+ name); }); / / can not specified type fun1 ((name) - > {System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- method performs the -- -- -- -- -- -- -- -- -- -- "+ name); }); / / can be omitted to write fun1 (name - > {System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- method performs the -- -- -- -- -- -- -- -- -- -- "+ name); }); } public static void fun1(MyInterFace myInterFace) { myInterFace.test1("admin"); }}Copy the code

4.4 No Return value for multiple parameters

@FunctionalInterface interface MyInterFace { void test1(String name,int age,Double price); } public class Test2 {public static void main(String[] args) { Just write code looks more comfortable fun1 ((name, age, price) - > {System. Out. Println (name + "= = = =" + age + "= = = =" + price); }); } public static void fun1(MyInterFace MyInterFace) {MyInterFace. Test1 ("admin",10,20D); }}Copy the code

4.5. A parameter has a return value

@FunctionalInterface interface MyInterFace { String test1(String name); } public class Test2 { public static void main(String[] args) { fun1(name -> { return name; }); } public static void fun1(MyInterFace myInterFace) { myInterFace.test1("admin"); }}Copy the code

4.6. Multiple parameters have return values

@FunctionalInterface interface MyInterFace { String test1(String name,String name2); } public class Test2 { public static void main(String[] args) { fun1((name,name2) -> { return name+name2; }); } public static void fun1(MyInterFace myInterFace) { System.out.println(myInterFace.test1("admin", "sd")); }}Copy the code

5. Stream and Lambda simple tests

public static void main(String[] args) { ArrayList<User> list = new ArrayList<>(); for (int i=0; i<=10; i++){ User user=new User(); user.setId(1l); User. SetUsername (" * * "+ I); user.setPassword("123"); list.add(user); } list.stream().forEach(e-> System.out.println(e.getUsername())); }Copy the code

Recommended reading

SpringBoot integration Druid

Hui Zhi Zhi Tang: the development of artifact EasyCode

Hui Zhi Zhi Tang: Baidu map interface to add coordinate points and routes

Hui Zhi Zhi Tang: SpringBoot integration QQ mail send