The zero-based Java 8

The zero-based Java 8

The Java 8 lists important Java 8 functions , and provides examples introduced in this release. All functions have a link to a detailed tutorial, such as lambda expressions, Java stream, time and date function interface API changes.

Java SE 8 to be released in early 2014 . In Java 8, functions most attention is the lambda expression. It also has many other important functions, such as the default method, Streaming API and the new date / time API. Let us by example to understand the 8 Java these new features .

1. Lambda Expressions

Lambda expressions for use Scala and other popular programming languages is no stranger to many of us. In the Java programming language, Lambda expressions (or function) is just a anonymous function , that is, with no name and is not limited function identifier. They are written precisely where needed, usually as arguments to other functions .

lambda expression basic syntax is:

either
(parameters) -> expression
or
(parameters) -> { statements; }
or
() -> expression

A typical example is shown below lambda expression:

(x, y) -> x + y  //This function takes two parameters and return their sum.

Please note that, depending on the type of x and y, the method may be used in multiple places. Parameters can match int or Integer or simply can match String. Depending on the context, it will add two integers or strings connecting the two.

Lambda expressions of writing rules

  1. Lambda expressions may have zero, one or more parameters.
  2. Type can be explicitly declared parameters may be inferred from the context.
  3. A plurality of mandatory parameters enclosed in parentheses and separated by commas. Empty empty parenthesis indicates a parameter set.
  4. When a single parameter, if deduce its type, parentheses are not enforced. E.g. a-> returns a * a.
  5. Lambda expressions of the body can contain zero, one or more statements.
  6. If the body of the lambda expression has a single statement, it is not necessary to use braces, and return type of the function anonymous expression returns the same body type. If more than one statement in the body, these statements must be enclosed in braces.

Read more: [the Java 8 the Lambda Expressions Tutorial]

2. Functional Interface

Function interface is also called a single interface to an abstract method (SAM interface) . As the name suggests, they allow the interior has an abstract method . Java 8 introduces a comment that @FunctionalInterfacewhen you violate the agreement annotated interface function interface, which can be used to annotate class compiler error.

A typical example of an interface function:

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

Note that even if @FunctionalInterfacethe comment is omitted, the interface function is also effective. It is only used to inform the compiler to enforce a single abstract method in the internal interface.

In addition, because the default method is not abstract, so you can freely to function interface add any number of default method .

Another important point to remember is that, if one of the common methods of abstract methods interface declaration covered java.lang.Object, the method does not count against the number of abstract methods of the interface, because any implementation of this interface will have come from java.lang.Objectthe achievement of other places . For example, the following function interface completely effective.

@FunctionalInterface
public interface MyFirstFunctionalInterface
{
    public void firstWork();
 
    @Override
    public String toString();                //Overridden from Object class
 
    @Override
    public boolean equals(Object obj);        //Overridden from Object class
}

Read more: [8 features the Java interfaces]

3. The default method

Java 8 allows you to add a non-abstract method in the interface. These methods must be declared as the default method. Java 8 default method introduced to enable the functionality of the lambda expression.

The default method allows you to add new functionality to the interface library, and to ensure that written for earlier versions of these interfaces binary code compatible.

Let's look at an example:

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

MoveableInterface defines a method, move()and provides a default implementation. If there is any class that implements this interface, it does not realize its own move()version of the method. It can be called directly instance.move(). E.g

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

If the class is willing to customize the move()behavior of the method, it can provide your own custom implementation and override this method.

Read more: [default method for the Java 8]

4. Java 8 stream

Java 8 Streams API introduces another major change, the Java 8 Streams API provides a mechanism for processing a set of data in a variety of ways, which may include filtering, transformation or any other application that may be useful manner.

Java Streams API supports 8 different types of iterations, the project sets where you can simply define to be processed, the operation of each project execution, and store the output of these operations.

API exemplary flow. In this example, itemsa Stringset of values that you want to delete an entry in some text at the beginning of the prefix.

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

Here items.stream()that we want to itemsuse the Streams API processing data collection.

Read more: [internal and external iteration of the Java 8]

5. Java 8 Date / Time API changes

The new date and time API / class (JSR-310), also known as ThreeTen , only change the way you handle dates in a Java application.

date

DateClass has even become obsolete. Date class is intended to replace the new class LocalDate, LocalTimeand LocalDateTime.

  1. This LocalDateclass represents a date. It did not indicate the time or time zone.
  2. This LocalTimeclass represents the time. He did not indicate the date or time zone.
  3. This LocalDateTimeclass represents a date - time. No time zone is represented.

If you want to use the date function area information, and then provide you with additional lambda 3 is similar to a class, that is above OffsetDate, OffsetTimeand OffsetDateTime. The time zone offset can be: or "Europe / Paris" shows the format of "30 +05." This is achieved by the use of another class is completed ZoneId.

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"));

Timestamp and duration

In order to represent a particular timestamp at any time, you need to use the classInstant . This Instantclass represents the time instant nanosecond precision. Immediate action including comparison with another Instantas well as to increase or decrease the duration.

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

DurationJava language class is the first to bring a new concept. It represents the difference between the two timestamps.

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

Read more: [8 Date and time of the Java API changes]

In the comments section of this your Java 8 tutorial left me problems.

Happy learning!

Guess you like

Origin www.cnblogs.com/huzidashu/p/11628476.html