Java8 01. New features

Lambda expressions

Lamba expressions may be familiar to those who have used other streaming programming languages; Lambda expressions (or functions) are just anonymous functions, that is, functions that have no name and no binding identifier. They are written exactly where they are needed, usually as arguments to other functions.

Basic syntax for lambda expressions:

Parameter expression (parameters) -> expression or (parameters) -> {statements; } or () -> expressionCopy the code

A typical example of a lambda expression is shown below

(x, y) -> x + y  
Copy the code

Rules for writing lambda expressions

  1. A lambda expression can have zero, one, or more arguments
  2. The type of the parameter can either be declared as displayed or inferred from the context
  3. Multiple parameters are enclosed in mandatory parentheses and separated by commas. Empty parentheses are used to represent a set of empty parameters
  4. When there is a single parameter, parentheses are not mandatory if the type is inferred.
  5. Lambda expressions can have zero, one, or more bodies
  6. If the subject of a lambda expression has a single statement, braces are not required, and the return type of the anonymous function is the same as the return type of the body expression. When there are multiple execution statements in the body, braces must be used to enclose the statements

2 Functional Interface

The more functional interfaces become single abstract method interfaces, they allow only one abstract method to be used inside them. Java8 introduced the annotation @functionInterface, which will cause an error at compile time when your annotated interface breaks the rules for functional interfaces.

The instance

@FunctionalInterface
public interface MyFirstFunctionalInterface {
    public void firstWork(a);
}

Copy the code

Note that the @functionalinterface annotation is also valid if omitted. It simply tells the compiler to enforce a single abstract method within the interface. Since the default method is not abstract, feel free to add default methods to your FunctionalInterface.

Another important point to remember is that if the interface declares an abstract method of one of the overriding public methods, java.lang.object, this will also not count toward the abstract method count, because any implementation of the interface will have an implementation from Java.lang.object or elsewhere. For example, the following are fully valid functional interfaces.

@FunctionalInterface public interface MyFirstFunctionalInterface { public void firstWork(); @Override public String toString(); @override public Boolean equals(Object obj); // Override method in Object without counting}Copy the code

3. Default method

Java8 allows you to add non-abstract methods to an interface, but those methods must be declared as default methods, and java8 introduced the ability for default methods to enable lambda expressions

example

public interface Moveable {
    default void move(a){
        System.out.println("I am moving");
    }

Copy the code

The Moveable interface defines a move method and provides a default implementation. If any class implements the move method, it can be called without implementing the move version of the interface

For example,

public class Animal implements Moveable{
    public static void main(String[] args){
        Animal tiger = new Animal();
        tiger.move();
    }
}
  
Output: I am moving
Copy the code

Of course, if you want to customize your own move methods, you can provide your own custom implementation and override methods.

4. Java8 flow

Stream is the biggest change in Java 8, providing a way to Stream data, including filtering, transforming, or any other way that might be useful to an application. The Stream API in Java 8 supports different types of iterations. Here is an example of the Steam API

List<String> items; String prefix; List<String> filteredList = items.stream().filter(e ->(! e.startsWith(prefix))).collect(Collectors.toList());Copy the code

Stream * is where we want items to use the Stream API to process the collection’s data

5. Date/time API changes

Date types are obsolete. Use LocalDate,LocalTime, and localDateTime

  • thisLocalDateClass represents a date. There is no representation of time or time zone.
  • theLocalTimeThe level represents time. There is no representation of dates or time zones.
  • thisLocalDateTimeClass represents a date-time. No time zone representation

Lambda expressions provide three additional classes like the above, OffsetDate,OffsetTime, and OffsetDateTime, if you want to use time and time zones at once. Time zones can be used in either “+8” or “Europe/Paris” format.

LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.of(12.20);
LocalDateTime localDateTime = LocalDateTime.now(); 
OffsetDateTime offsetDateTime = OffsetDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
Copy the code
Timestamp and duration

To represent a specific timestamp at any moment, you need to use Instant, where the Instant class represents a precise moment of time nanosecond. Operations on Instant include comparing Instant with another and adding or subtracting durations.

Instant instant = Instant.now(); Instant instant1 = instant.plus(Duration.ofMillis(5000)); Instant instant2 = instant.minus(Duration.ofMillis(5000)); Instant instant3 = instant.minusSeconds(10);
Copy the code

Duration is a permission concept first introduced in Java 8 and represents the time difference between two timestamps.

Duration duration = Duration.ofMillis(5000); duration = Duration.ofSeconds(60); duration = Duration.ofMinutes(10);
Copy the code

Duration deals with small times, such as milliseconds, seconds, minutes, and time. To get a longer Duration, use the Period class

Period period = Period.ofDays(6); period = Period.ofMonths(6); period = Period.between(LocalDate.now(), LocalDate.now().plusDays(60));
Copy the code