features

  • Lambda expressions ** allow functions to be passed as arguments to a method

  • Functional interfaces have one and only abstract method, but can have multiple non-abstract method interfaces.

  • ** Default methods ** interfaces can have implementation methods and do not need implementation classes to implement their methods.

  • ** Method references ** You can directly reference methods or constructors of existing Java classes or objects (instances)

  • StreamApI enhancements to Collection objects

  • **Date Time API ** Enhances Date and Time handling

  • The Optional class resolves null pointer exceptions.

Lambda expressions

Lambda expressions, also known as closures. Allows a function to be passed as an argument to a method. Lambda consists of a comma separated argument list, a -> symbol, and a function body.

Syntax :(parameters) -> expression or (parameters) ->{statements; }

public interface PersonCallBack { void callback(); Public void test(String name, PersonCallBack callBack) {system.out.println (name); callBack.callback(); } public static void main(String[] args) {new Person().test(" 三", () -> {system.out.println ("18"); }); }Copy the code

You need to declare the PersonCallBack interface as a functional interface. That is, there is only one abstract method in the interface. Lambda expressions actually implement the interface and implement the only method in the interface.

  • ** Optional type declaration: ** There is no need to declare parameter types, and the compiler can uniformly recognize parameter values.
  • ** Optional parameter parentheses: ** You do not need to define parentheses for one parameter, but you do need to define parentheses for multiple parameters.
  • ** Optional braces: ** If the body contains a statement, braces are not required.
  • ** The compiler automatically returns the value if the body has only one expression return value. Using curly braces requires specifying that the expression returns a numeric value.

Note: lambda expressions can only refer to outer local variables that mark final, which means that local variables defined outside of the domain cannot be modified inside the lambda, otherwise a compilation error will occur.

Functional interface

A Functional Interface is an Interface that has one and only abstract method, but can have multiple non-abstract methods. @functionalInterface validates functional interfaces.

There are many new functional interfaces in java8. In the java.util.function package. Makes it easier to use the Lambda interface. Common interfaces are listed below.

Default methods and static methods

Methods that use the default modifier in an interface are the default. Methods decorated with static are static methods.

Default methods and static methods are interfaces that can have implementation methods and do not need implementation classes to implement their methods. Implementation classes can also implement methods to override.

Why have this feature?

First, the previous interface was a double-edged sword, with the benefit of being abstract-oriented rather than programming-oriented. The drawback was that when you needed to change the interface, you needed to change all the classes that implemented it. The current collection framework prior to Java 8 didn’t have the foreach method. The usual solution is to add new methods and implementations to the relevant interfaces in the JDK. However, for a released version, there is no way to add new methods to the interface without affecting existing implementations. So the default method introduced. Their purpose is to solve the problem of interface modifications that are incompatible with existing implementations.

Method references

Method references refer to a method by its name, using a pair of colons ::.

The argument list of a method must be identical to the argument list of an abstract method of a functional interface, and the return value is not required.

  • Reference method

  • Instance object :: Instance method name instance::method

    Consumer<String> consumer = System.out::println; Consumer. Accept (" ޮ zhang SAN ");Copy the code
  • **Class name ::static method name **Class::static_method

    Function<Long, Long> f = Math::abs; 
    Long result = f.apply(-3L);
    Copy the code
  • Class name :: Instance method name Class::method

    BiPredicate<String, String> b = String::equals; 
    b.test("a", "b");
    Copy the code
  • Reference constructor Class::new

    Supplier<Person> supplier = Person::new;   
    Person person = supplier.get();
    Copy the code
  • Reference to an array

    Function<Integer, int[]> fun = int[]::new; 
    int[] arr = fun.apply(10);
    Copy the code

Optional class

The Optional class is a container object that can be null. The isPresent() method returns true if the value exists, and calling the get() method returns the object.

There are several ways to create an Optional object:

  1. Optional.of(T value), returns an Optional object. Value cannot be null, otherwise a null pointer will be raised

  2. Option. ofNullable(T value), returns an Optional object whose value can be null

  3. Option.empty (), which means empty

Other apis

  • Option.ispresent (), whether there is a value (not null)

  • optional.ifPresent(Consumer<? Super T> consumer), execute consumer if a value exists

  • Option.get (), get value

  • Optional. orElse(T other), return other if there is no value

  • optional.orElseGet(Supplier<? Extends T> other), executes other and returns if there is no value

  • optional.orElseThrow(Supplier<? ExceptionSupplier extends X> exceptionSupplier), executes exceptionSupplier if there is no value and throws an exception

Note:

When using Optional, try not to call option.get (), option.isPresent () directly. Rely on other methods like option.orelse (), option.orelseget (), etc.

Stream API

Juejin. Cn/post / 688105…

Date Time API

Java 8 further enhances Date and Time handling with the release of a new date-time API (JSR 310).

Java8 before

  • Non-thread-safe Java.util. Date is non-thread-safe and all Date classes are mutable

  • ** Poorly designed ** Date/time classes are inconsistently defined and have date classes in both java.util and java.sql packages.

  • The date class does not provide internationalization and has no time zone support

The new java.time package covers all operations that handle date, time, date/time, time zone, instants, during, and clock.

LocalDate class

LocalDate contains only the date part in ISO-8601 format without time zone information

LocalDate now = LocalDate.now(); // 2020-10-08 now = now.plusDays(2); // 2020-10-10 now = now.plusMonths(1); // 2020-11-10 now = now.minusMonths(1); // 2020-10-10 now = now.minusDays(2); // 2020-10-08 LocalDate date3 = LocalDate.of(2020, Month.DECEMBER, 12); / / 2020-12-12Copy the code

Gets the current date and modifies it

LocalTime class

LocalTime only holds the time part in ISO-8601 format without time zone information

LocalTime now = LocalTime.now(); // 22:10:54.613 now = now. PlusMinutes (12); // 22:22:54.613 now = now. MinusHours (2); / / 20:22:54. 613 System. Out. Println (now. The format (DateTimeFormatter. OfPattern (" HH: mm: ss "))); // 20:22:54 LocalTime date4 = LocalTime.of(22, 15, 30); // 20:15:30 LocalTime date5 = LocalTime.parse("20:15:30"); / / 20:15:30Copy the code

Gets the current time and modifies it

LocalDateTime class

LocaleDateTim combines the functionality of LocaleDat and LocalTime

ZonedDateTime class

Gets the current date and time from the system clock in the specified time zone.

ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles")); System.out.println(now); / / the 2020-10-08 T07: when 754-07:00 America/Los_AngelesCopy the code

Get the current Time Zone

ZoneId currentZone = ZoneId.systemDefault(); System.out.println(" currentZone: "+ currentZone); // Current time zone: Asia/ShanghaiCopy the code

Clock class

It gets the current time, date and time by specifying a time zone

Clock shanghai = Clock.system(ZoneId.of("Asia/Shanghai")); System.out.println(LocalDateTime.now(shanghai)); / / T22:2020-10-08 and. 999Copy the code

Duration class

Duration Calculates the difference between two dates

LocalDateTime start = LocalDateTime.parse("2020-01-01 22:10:10", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); LocalDateTime end = LocalDateTime.parse("2020-02-01 22:15:10", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); Duration duration = Duration.between(start, end); System.out.println(duration.toDays()); // 31 System.out.println(duration.toHours()); / / 744Copy the code