Make writing a habit together! This is the fifth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

Moving on from the first new Java8 feature, let’s talk about some of the other new features.

4. New date and time API

4.1LocalDate, LocalTime, LocalDateTime

The LocalDate, LocalTime, and LocalDateTime classes are some of the more important classes. Their instances are immutable objects representing the date, time, date, and time using the ISO-8601 calendar system, respectively. They provide a simple local date or time and do not contain current time information or time-zone specific information.

Note: the ISO-8601 calendar system is a modern citizen’s representation of dates and times developed by the International Organization for Standardization, also known as the Gregorian calendar.

4.2 Instant Time point

  • When dealing with time and date, we usually think of years, months, days, hours, minutes and seconds. However, this is only a model of time, which is for humans. The second general-purpose model is machine-oriented, or continuous. In this model, a point in the timeline is represented as a large number, which is convenient for computer processing. In UNIX, this number starts in 1970 and is measured in seconds; Similarly, in Java, it started in 1970, but in milliseconds.

  • The java.time package provides a machine view through the value type Instant and does not provide units of time in the human sense. Instant represents a point on the timeline without requiring any contextual information, such as time zone. Conceptually, it simply represents the number of seconds since 00:00:0 (UTC) on January 1, 1970. Because the Java.time package is calculated on a nanosecond basis, Instant can achieve nanosecond accuracy. (1 ns = 10-9 s) 1 second = 1000 ms =10^6 microseconds =10^9 nanoseconds

4.3 Formatting and Parsing the date or time

Java. Time. The format. DateTimeFormatter class: this class format provides three methods:

  • Predefined standard formats. Such as: ISO_LOCAL_DATE_TIME; ISO_LOCAL_DATE
  • Localize relevant formats. Such as: ofLocalizedDate (FormatStyle. FULL)
  • Custom format. Example: ofPattern(” YYYY-MM-DD hh: MM: SS E “)

5. Use of Optional classes

The notorious null-pointer exception is by far the most common cause of Java application failure. In the past, Google’s famous Guava project introduced the Optional class to address null pointer exceptions. Guava encourages programmers to write cleaner code by checking for null values to prevent code contamination. Inspired by Google Guava, the Optional class has become part of the Java 8 class library.

Optional is actually a container: it can hold values of type T, or just NULL. Optional provides a number of useful methods so that we don’t have to explicitly null-check.

The Javadoc for the Optional class is described as follows: This is a null-capable container object. The isPresent() method returns true if the value exists, and calling the get() method returns the object.

The Optional

class (java.util.Optional) is a container class that represents the presence or absence of a value. Null-pointer exceptions can also be avoided.

Common methods:

  • Option.empty () : Creates an empty Optional instance

  • Option. of(T T) : Creates an Optional instance

  • Option. ofNullable(T T): If T is not null, create an Optional instance; otherwise, create an empty instance

  • IsPresent () : checks whether a value is included

  • T get(): Returns the value if the calling object contains it, otherwise throws an exception

  • OrElse (T T) : Returns the value if the calling object contains it, T otherwise

  • OrElseGet (Supplier s) : Returns the value if the calling object contains it, otherwise returns the value obtained by S

  • Map (Function f): if it has a value, and returns the processed Optional, otherwise

Optional.empty()

  • FlatMap (Function mapper): Similar to map, the return value must be Optional

6. Lambda expressions

Lambda is an anonymous function, and we can think of a Lambda expression as a piece of code that can be passed (passing code like data). It allows you to write cleaner, more flexible code. As a more compact code style, the language expression ability of Java has been improved.

6.1 Lambda expressions

  • Conversion from anonymous classes to Lambda example 1:

Using Lambda expressions:

  • Conversion from anonymous classes to Lambda example 2

Using Lambda expressions:

Lambda expression syntax

Lambda expressions: A new syntax element and operator introduced in the Java 8 language. The operator is “->”, which is called the Lambda operator or arrow operator. It breaks Lambda into two parts:

Left: Specifies the list of arguments required by the Lambda expression

On the right: specifies the Lambda body, which is the implementation logic of the abstract method and what Lambda expressions are supposed to do.

Syntax Format 1:No parameter, no return value

Syntax Format 2:Lambda takes one argument, but has no return value.

Syntax Format 3: The data type can be omittedBecause it can be inferred by the compiler, it is called type inference

Syntax Format 4:When Lambda requires only one argument, the parentheses of the argument can be omitted

Syntax Format 5:Lambda takes two or more arguments, multiple execution statements, and can have a return value

Syntax Format 6:When the Lambda body has only one statement, the return and braces, if present, can be omitted

The types of arguments in Lambda expressions above are inferred by the compiler. Programs can compile without specifying a type in a Lambda expression, because Javac behind the scenes deduces the type of the argument based on the context of the program. The type of a Lambda expression is context-dependent and inferred by the compiler. That’s what it’s called"Type inference".

6.2 Functional interfaces

What is a Functional interface

  • Contains onlyAn abstract methodtheinterface, known as theFunctional interface.
  • You can use Lambda expressions to create objects for this interface. If a Lambda expression throws a checked exception (that is, a non-runtime exception), the exception needs to be declared on the abstract method of the target interface.
  • We can use it on one interface@FunctionalInterfaceAnnotations, to check if it is a functional interface. Javadoc also contains a declaration that the interface is a functional interface.
  • injava.util.functionPackage defines Java 8’s rich functional interfaces

Examples of functional interfaces

Custom functional interfaces Using generics in functional interfaces:

Pass Lambda expressions as arguments

Passing Lambda expressions as arguments:

Pass a Lambda expression as a parameter: In order to pass a Lambda expression as a parameter, the parameter type that receives the Lambda expression must be the type of the functional interface compatible with the Lambda expression.

Java has four core functional interfaces built in

6.3 Method references and constructor references

Method References

  • When you want to pass toLambdaBody of the operation, there is already a method to implement, can use method reference!
  • Method references areLambdaAn expression, which is an instance of a functional interface, refers to a method by its nameLambdaA syntactic sugar for an expression.
  • Requirements: implement abstract methodsThe list of parametersandReturn value type, must be referenced with the method’s parameter list and return value typeconsistent!
  • Method references: Uses the operator": :"Separates the class (or object) from the method name.

There are three main uses:

  • Object :: Instance method name
  • Class :: Static method name
  • Class :: Instance method name

Method references

Such as:

Is equal to:

Such as:

Is equal to:

Note: When the first argument to a functional interface method is the caller that needs to reference the method, and the second argument is the argument (or no argument) that needs to reference the method: ClassName::methodName

Constructor reference

Format: the ClassName: : new

Combined with a functional interface, automatically compatible with methods in the functional interface. Constructor references can be assigned to defined methods, requiring that the constructor argument list matches the argument list of the abstract method in the interface! And the return value of the method is the object of the constructor class.

Such as:

Is equal to:

An array reference

Format: type[] :: new

Such as:

Is equal to: