Study Notes: New Features of Java8 for Dark Horse Programmers

Java language introduction to mastery chapters

  1. Study notes: Java-Basics (Part 1)_ljtxy.love’s blog-CSDN blog
  2. Study Notes: Java-Intermediate (Part 2)_ljtxy.love’s Blog-CSDN Blog
  3. Study Notes: Java-Advanced Chapter (Part 3)_ljtxy.love’s Blog-CSDN Blog
  4. Study Notes: Java-Advanced Chapter (1) (Part 4)_ljtxy.love's Blog-CSDN Blog
  5. Study Notes: Java-Advanced Chapter (2) (Part 5)_ljtxy.love’s Blog-CSDN Blog
  6. Study Notes: New Features of Java8_ljtxy.love’s Blog-CSDN Blog

1 Overview

Summary of notes:

  1. Overview: New features emerging in JDK1.8
  2. New features:
    • lambda expression
    • method reference
    • Default method
    • Stream API
    • Date Time API
    • Optional class
    • ……

1.1 Meaning

Java 8 (also known as jdk 1.8) is a major version of Java language development. Oracle released Java 8 on March 18, 2014, which supports functional programming, new JavaScript engine, new date API, new Stream API, etc.

1.2 New features

  • Lambda expression − Lambda allows a function to be passed as a parameter to a method (a function is passed as a parameter to a method).
  • Method reference − Method reference provides a very useful syntax for directly referencing methods or constructors of existing Java classes or objects (instances). Used in conjunction with lambda, method references can make the language structure more compact and concise and reduce redundant code.
  • Default method − A default method is a method that has an implementation in the interface.
  • New tools − New compilation tools, such as: Nashorn engine jjs, class dependency analyzer jdeps.
  • Stream API − The newly added Stream API (java.util.stream) brings true functional programming style to Java.
  • Date Time API − Enhance the processing of date and time.
  • Optional class − The Optional class has become a part of the Java 8 class library to handle null pointer exceptions.
  • Nashorn, JavaScript engine − Java 8 provides a new Nashorn javascript engine, which allows us to run specific javascript applications on the JVM.

illustrate:

2.Lambda expression

Summary of notes:

  1. Overview: Make the code more concise and compact

  2. grammar:

    • 实现的这个接口中的抽象方法中的形参列表 -> 抽象方法的处理
      // 例如
      (parameters) -> expression
      (parameters) ->{
               
                statements; }
      
  3. Variable scope:

    • Attempting to modify local variables modified by the Final keyword in a Lambda expression is not allowed
    • It is not allowed to declare a parameter or local variable with the same name as a local variable in a lambda expression.

2.1 Overview

Lambda expressions, also known as closures, are the most important new features driving the release of Java 8. Lambda allows functions to be passed as arguments to a method (functions are passed into methods as arguments). Using Lambda expressions can make the code more concise and compact.

2.2 Grammar

​A syntax introduced after JDK1.8. It is written using a ->symbol. The arrow divides the Lambda expression into left and right parts. What is written on the left is the formal parameter list in the abstract method in the interface implemented, and what is written on the right is Handling of abstract methods;

实现的这个接口中的抽象方法中的形参列表 -> 抽象方法的处理
// 例如
(parameters) -> expression
(parameters) ->{
    
     statements; }

illustrate:

  • **Optional type declaration:** There is no need to declare parameter types, the compiler can uniformly identify parameter values
  • **Optional parameter parentheses:** There is no need to define parentheses for one parameter, but multiple parameters need to define parentheses.
  • **Optional braces:** If the body contains a statement, braces are not required
  • **Optional return keyword:** If the body has only one expression return value, the compiler will automatically return the value. The curly braces need to specify that the expression returns a value.

2.3 Basic use cases

// 1. 不需要参数,返回值为 5  
() -> 5  
  
// 2. 接收一个参数(数字类型),返回其2倍的值  
x -> 2 * x  
  
// 3. 接受2个参数(数字),并返回他们的差值  
(x, y) -> x – y  
  
// 4. 接收2个int型整数,返回他们的和  
(int x, int y) -> x + y  
  
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)  
(String s) -> System.out.print(s)

Reference link: Detailed explanation of Lambda expressions in Java_java lambda expression_Tomorrow, Hello Blog-CSDN Blog

public class Java8Tester {
    
    
   public static void main(String args[]){
    
    
      Java8Tester tester = new Java8Tester();
        
      // 类型声明 -----注意,此处是重写了接口,并用Lambda表达式进行简化后的写法
      MathOperation addition = (int a, int b) -> a + b;
        
      // 不用类型声明
      MathOperation subtraction = (a, b) -> a - b;
        
      // 大括号中的返回语句
      MathOperation multiplication = (int a, int b) -> {
    
     return a * b; };
        
      // 没有大括号及返回语句
      MathOperation division = (int a, int b) -> a / b;
        
      System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
      System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
      System.out.println("10 / 5 = " + tester.operate(10, 5, division));
        
      // 不用括号
      GreetingService greetService1 = message ->
      System.out.println("Hello " + message);
        
      // 用括号
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
        
      greetService1.sayMessage("Runoob");
      greetService2.sayMessage("Google");
   }
    
    @FunctionalInterface // 函数式接口注解(只包含一个抽象方法的接口,称为函数式接口)
   interface MathOperation {
    
    
      int operation(int a, int b);
   }
    @FunctionalInterface
   interface GreetingService {
    
    
      void sayMessage(String message);
   }
    
   private int operate(int a, int b, MathOperation mathOperation){
    
    
      return mathOperation.operation(a, b);
   }
}

Notice:

  • Lambda expressions are mainly used to define functional interfaces for inline execution
  • Lambda expressions eliminate the trouble of using anonymous methods and give Java simple but powerful functional programming capabilities.

2.4 Variable scope

2.4.1 Member variables

Meaning: Attempting to modify local variables in a Lambda expression is not allowed

public class Java8Tester {
    
    
 
   final static String salutation = "Hello! ";
   // static String salutation = "Hello! ";  可以修改
   // static String salutation = "Hello! ";  可以修改
   
   public static void main(String args[]){
    
    
      GreetingService greetService1 = message -> System.out.println(salutation + message);
      // GreetingService greetService1 = message -> System.out.println(salutation ="Test");
      greetService1.sayMessage("Runoob");
   }
    
   interface GreetingService {
    
    
      void sayMessage(String message);
   }
}

illustrate:

  • You can access outer local variables in lambda expressions
  • The outer local variable modified by Final cannot be modified in a lambda expression.

2.4.2 Local variable parameters

Meaning: It is not allowed to declare a parameter or local variable with the same name as a local variable in a Lambda expression.

String first = "";  
Comparator<String> comparator = (first, second) -> Integer.compare(first.length(), second.length()); 

illustrate:

​ Compilation error will occur, first has been defined repeatedly

3.Method reference

Summary of notes: Already learned, please refer to this set of notes for details, Java Advanced Chapter

4. Functional interface

Summary of notes:

  1. Overview: Functional interfaces can be implicitly converted into lambda expressions to simplify code and improve code readability and maintainability.

  2. Functional interface:

    1. Consumer interface (Consumption interface)

      Consumer<String> consumer = s -> System.out.println(s);
      consumer.accept("Hello world");
      

      Description: Accepts an input parameter and has no return value

    2. Supplier interface (production interface)

      Supplier<String> supplier = () -> "Hello world";
      String str = supplier.get();
      System.out.println(str);
      

      Description: Accepts an input parameter and returns a result

    3. Function interface (functional interface)

      Function<String, Integer> function = s -> s.length();
      int length = function.apply("Hello world");
      System.out.println(length);
      

      Description: Accepts an input parameter and returns a result

    4. Predicate interface (assertive interface)

      Predicate<String> predicate = s -> s.length() > 5;
      boolean result = predicate.test("Hello world");
      System.out.println(result);
      

      Description: Accepts an input parameter and returns a Boolean value

4.1 Overview

4.1.1 Meaning

​ A functional interface is an interface that has one and only one abstract method , but can have multiple non-abstract methods. Functional interfaces can be implicitly converted to lambda expressions. Lambda expressions and method references (actually also considered Lambda expressions).

4.1.2 Definition

​ Place @Functionallnterface on the interface. If the interface is a functional interface, the compilation will pass; if not, the compilation will fail.

Example:

@FunctionalInterface
    interface GreetingService {
    
    
        void sayMessage(String message);
    }
// 实现
GreetingService greetService1 = message -> System.out.println("Hello " + message);

illustrate:

​ The way to write Lambda expressions requires a functional interface to be abbreviated.

4.2 Commonly used functional interfaces

image-20230504102842256

4.2.1Consumer interface

4.2.1.1 Overview

​ Consumer<T> interface is also called consumer interface. The data type it consumes is specified by generics.

4.2.1.2 Common methods

Consumer<T>: Contains two methods.

  • void accept(T t): Perform this operation on the given parameters
  • default Consumer < T > andThen(Consumer after): Returns a combined Consumer, performs this operation in sequence, and then performs the after operation

4.2.1.3 Basic use cases

@FunctionalInterface
public interface Consumer<T> {
    
    
    void accept(T t);
}
// 例如
Consumer<String> consumer = s -> System.out.println(s);
consumer.accept("Hello world");

illustrate:

​Accepts one input parameter and has no return value

4.2.1.4 Underlying source code

image-20230504103333026

4.2.2Supplier interface

4.2.2.1 Overview

​ Supplier<T> interface is also called a production interface. If we specify what type of generic type the interface is, then the get method in the interface will generate what type of data for us to use.

4.2.2.2 Common methods

  • T get(): Get the result

4.2.2.3 Basic use cases

@FunctionalInterface
public interface Supplier<T> {
    
    
    T get();
}
// 例如
Supplier<String> supplier = () -> "Hello world";
String str = supplier.get();
System.out.println(str);

illustrate:

​ Provide an output parameter, no input parameters

4.2.2.4 Underlying source code

image-20230504103720208

4.2.3Function interface

4.2.3.1 Overview

​ Function<T,R>: The interface is usually used to process and convert parameters (the processing logic is implemented by Lambda expressions), and then return a new value

4.2.3.2 Common methods

  • R apply(T t): applies this function to the given arguments
  • default< V >: Function andThen(Function after): Returns a combined function that first applies the function to the input and then applies the after function to the result

4.2.3.3 Basic use cases

@FunctionalInterface
public interface Function<T, R> {
    
    
    R apply(T t);
}
// 例如
Function<String, Integer> function = s -> s.length();
int length = function.apply("Hello world");
System.out.println(length);

illustrate:

​Accepts an input parameter and returns a result

4.2.3.4 Underlying source code

image-20230504104503508

4.2.4Predicate interface

4.2.4.1 Overview

​ Predicate<T>: The interface is usually used to determine whether the parameters meet the specified conditions.

4.2.4.2 Common methods

  • boolean test(T t): Judge the given parameters (the judgment logic is implemented by Lambda expression) and return a Boolean value
  • default Predicate< T > negate(): Returns a logical negation, corresponding to logical negation
  • default Predicate< T > and(): Returns a combined judgment, corresponding to short-circuit and
  • default Predicate< T > or(): Returns a combined judgment, corresponding to short circuit or
  • isEqual(): Tests whether two parameters are equal

4.2.4.3 Basic use cases

@FunctionalInterface
public interface Predicate<T> {
    
    
    boolean test(T t);
}
// 例如
Predicate<String> predicate = s -> s.length() > 5;
boolean result = predicate.test("Hello world");
System.out.println(result);

illustrate:

​Accepts an input parameter and returns a Boolean value

4.2.4.4 Underlying principles

image-20230504104728281

5.Default method

Summary of notes:

  1. Overview: The default method is that the interface can have implementation methods, and there is no need for an implementation class to enforce its methods.

  2. grammar:

    public interface Vehicle {
           
           
       default void print(){
           
           
          System.out.println("我是一辆车!");
       }
    }
    
  3. Multiple default methods: If you implement multiple interfaces and the methods of the interfaces have the same name, you can override this method or call the specified interface through the Super keyword.

    public class Car implements Vehicle, FourWheeler {
           
           
       public void print(){
           
           
          Vehicle.super.print();
       }
    }
    
  4. Static default method: Static default method, which can be called directly and does not force overriding of this method

    public interface Vehicle {
           
           
          // 静态方法
       static void blowHorn(){
           
           
          System.out.println("按喇叭!!!");
       }
    }
    

5.1 Overview

5.1.1 Meaning

Java 8 adds new default methods to interfaces. Simply put, the default method is that the interface can have implementation methods, and there is no need for an implementation class to enforce its methods. We only need to add the default keyword in front of the method name to implement the default method.

5.1.2 Function

​ The default method of entering. Their purpose is to solve the problem of incompatibility between interface modifications and existing implementations

5.2 Grammar

public interface Vehicle {
    
    
   default void print(){
    
    
      System.out.println("我是一辆车!");
   }
}

illustrate:

​ Add the default keyword to the interface

5.3 Multiple default methods

When a class implements multiple interfaces and the methods in the interfaces have the same name, you can override the interface method or make a specific call through the super keyword.

// 接口
public interface Vehicle {
    
    
   default void print(){
    
    
      System.out.println("我是一辆车!");
   }
}
 
public interface FourWheeler {
    
    
   default void print(){
    
    
      System.out.println("我是一辆四轮车!");
   }
}
// 重写接口默认方法
public class Car implements Vehicle, FourWheeler {
    
    
   default void print(){
    
    
      System.out.println("我是一辆四轮汽车!");
   }
}
// 通过super调用指定接口的默认方法
public class Car implements Vehicle, FourWheeler {
    
    
   public void print(){
    
    
      Vehicle.super.print();
   }
}

5.4 Static default methods

public interface Vehicle {
    
    
   default void print(){
    
    
      System.out.println("我是一辆车!");
   }
    // 静态方法
   static void blowHorn(){
    
    
      System.out.println("按喇叭!!!");
   }
}

illustrate:

  • Static methods in the interface can be called directly

  • Example:

     Vehicle.blowHorn();
    

6.Stream

Summary of notes: Already learned, please refer to this set of notes for details, Java Advanced Chapter

7.Optional class

Summary of notes:

  1. Overview:
    1. Meaning: The Optional class is a container object that can be null
    2. Function: It can solve the null pointer exception very well
  2. Common member methods:
    1. Get Optional object:
      • ofNullable : If it is non-null, return the specified value described by Optional, otherwise return empty Optional
      • of : Returns an Optional specifying a non-null value
    2. Judgment value exists:
      • isPresent : The method will return true if the value exists, otherwise it will return false.
      • isEmpty : The method will return true if the value does not exist, otherwise it will return false.
      • orElse : If the value exists, return the value, otherwise return other
    3. Get value:
      • get : If this value is contained in this Optional, return the value, otherwise throw an exception: NoSuchElementException

7.1 Overview

7.1.1 Meaning

The Optional class is a container object that can be null. If the value exists, the isPresent() method will return true, and calling the get() method will return the object. ptional is a container: it can hold a value of type T, or just null. Optional provides many useful methods so that we don't have to explicitly detect null values.

7.1.2 Function

The introduction of the Optional class solves the null pointer exception very well

7.2 Common member methods

serial number Method & Description
1 **static Optional empty()** returns an empty Optional instance.
2 **boolean equals(Object obj)** determines whether other objects are equal to Optional.
3 **Optional filter(Predicate<? super predicate)** If the value exists and the value matches the given predicate, return an Optional to describe the value, otherwise return an empty Optional.
4 ** Optional flatMap(Function<? super T,Optional > mapper)** If the value exists, returns the value based on the mapping method contained in Optional, otherwise returns an empty Optional
5 **T get()** If this value is contained in this Optional, return the value, otherwise throw an exception: NoSuchElementException
6 **int hashCode()** returns the hash code of the existing value, or 0 if the value does not exist.
7 **void ifPresent(Consumer<? super T> consumer)** If the value exists, call the consumer with the value, otherwise do nothing.
8 **boolean isPresent()**The method returns true if the value exists, otherwise it returns false.
9 ** Optional map(Function<? super T,? extends U> mapper)** If there is a value, execute the mapping function on it to get the return value. If the return value is not null, create an Optional containing the map return value as the map method return value, otherwise an empty Optional is returned.
10 **static Optional of(T value)** returns an Optional specifying a non-null value.
11 **static Optional ofNullable(T value)** If it is non-null, returns the specified value described by Optional, otherwise returns an empty Optional.
12 **T orElse(T other)**If the value exists, return the value, otherwise return other.
13 **T orElseGet(Supplier<? extends T> other)**If the value exists, return the value, otherwise trigger other and return the result of other call.
14 ** T orElseThrow(Supplier<? extends X> exceptionSupplier)** If the value exists, return the contained value, otherwise throw the exception inherited by Supplier
15 **String toString()** returns an Optional non-empty string for debugging

7.3 Basic use cases

import java.util.Optional;
 
public class Java8Tester {
    
    
   public static void main(String args[]){
    
    
   
      Java8Tester java8Tester = new Java8Tester();
      Integer value1 = null;
      Integer value2 = new Integer(10);
        
      // Optional.ofNullable - 允许传递为 null 参数
      Optional<Integer> a = Optional.ofNullable(value1);
        
      // Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException
      Optional<Integer> b = Optional.of(value2);
      System.out.println(java8Tester.sum(a,b));
   }
    
   public Integer sum(Optional<Integer> a, Optional<Integer> b){
    
    
    
      // Optional.isPresent - 判断值是否存在
        
      System.out.println("第一个参数值存在: " + a.isPresent());
      System.out.println("第二个参数值存在: " + b.isPresent());
        
      // Optional.orElse - 如果值存在,返回它,否则返回默认值
      Integer value1 = a.orElse(new Integer(0));
        
      //Optional.get - 获取值,值需要存在
      Integer value2 = b.get();
      return value1 + value2;
   }
}

8.Rhino JavaScript

Summary of notes: Nashorn JavaScript Engine is no longer available in Java 15, so please refer to: Java 8 Nashorn JavaScript | Novice Tutorial (runoob.com)

9. Date and time API

Summary of notes: Already learned, please refer to this set of notes for details, Java Advanced Chapter

10.Base64 encoding

Summary of notes:

  1. Overview: Base64 is an encoding used to encode binary data into ASCII characters
  2. Classification:
    • Basic:
      1. Encoder
      2. Decoder
    • URL:
      1. getUrlEncoder
      2. getUrlDecoder
    • MIME
      1. getMimeEncoder
      2. getMimeDecoder

10.1 Overview

10.1.1 Meaning

In Java 8, Base64 encoding has become the standard for Java class libraries. The Base64 class is provided in Java8 to support Base64 encoding and decoding

10.1.2 Function

Base64 is an encoding method used to encode binary data into ASCII characters. It is often used to convert binary data into readable strings during network transmission.

10.1.3 Classification

The Base64 tool class provides a set of static methods to obtain the following three BASE64 codecs:

  • **Basic:** The output is mapped to a set of characters A-Za-z0-9+/, the encoding does not add any line markers, and the decoding of the output only supports A-Za-z0-9+/
  • **URL:** The output maps to a set of characters A-Za-z0-9+_, the output is a URL and a file
  • **MIME:** Output is mapped to a MIME-friendly format. The output should be no more than 76 characters per line and separated by '\r' followed by '\n'. There is no line splitting at the end of the encoded output

10.2 Embedded classes

serial number Embedded classes & descriptions
1 static class Base64.Decoder This class implements a decoder for decoding byte data using Base64 encoding.
2 static class Base64.Encoder This class implements an encoder that uses Base64 encoding to encode byte data.

10.3 Common member methods

serial number Method name & description
1 **static Base64.Decoder getDecoder()** returns a Base64.Decoder, which uses the basic base64 encoding scheme for decoding .
2 **static Base64.Encoder getEncoder()** returns a Base64.Encoder, and the encoding uses the basic base64 encoding scheme.
3 **static Base64.Decoder getMimeDecoder()** returns a Base64.Decoder, which uses the MIME-type base64 encoding scheme for decoding.
4 **static Base64.Encoder getMimeEncoder()** returns a Base64.Encoder, and the encoding uses the MIME-type base64 encoding scheme.
5 **static Base64.Encoder getMimeEncoder(int lineLength, byte[] lineSeparator)** returns a Base64.Encoder. The encoding uses the MIME base64 encoding scheme. The length of each line and the line separator can be specified through parameters.
6 **static Base64.Decoder getUrlDecoder()** returns a Base64.Decoder that decodes using URL- and filename-safe base64 encoding schemes.
7 **static Base64.Encoder getUrlEncoder()** returns a Base64.Encoder, encoding using URL and file name safe base64 encoding scheme.

10.4 Basic use cases

public class Java8Tester {
    
    
    public static void main(String args[]){
    
    
        try {
    
    
            // 基本编码
            String base64encodedString = Base64.getEncoder().encodeToString("runoobjava8".getBytes("utf-8"));
            System.out.println("Base64 编码字符串 (基本) :" + base64encodedString);

            // 基本解码
            byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);

             // URL 和文件名安全型 编码
            System.out.println("原始字符串: " + new String(base64decodedBytes, "utf-8"));
            base64encodedString = Base64.getUrlEncoder().encodeToString("runoob?java8".getBytes("utf-8"));
            System.out.println("Base64 编码字符串 (URL) :" + base64encodedString);

             // MIME 型 编码
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < 10; ++i) {
    
    
                stringBuilder.append(UUID.randomUUID().toString());
            }

            byte[] mimeBytes = stringBuilder.toString().getBytes("utf-8");
            String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);
            System.out.println("Base64 编码字符串 (MIME) :" + mimeEncodedString);

        }catch(UnsupportedEncodingException e){
    
    
            System.out.println("Error :" + e.getMessage());
        }
    }
}

Guess you like

Origin blog.csdn.net/D_boj/article/details/132257818