JAVA8 Lamda function

1 lamda function concept

  Simply understood as an anonymous function:

   public int add(int x, int y) {
        return x + y;
    }

 Turn into lamda function: (int x, int y) -> x + y;  

 Or (x, y) -> x + y; compiler automatically recognize the type of the parameter

 

Type 2 lamda

Type lamda expressions, called "target type (target type)". Lamda expression is the target type "function interface (functional interface)" Java8 was introduced.

An interface, an abstract method only if explicitly declared, then it is a function interface.

Usually @FunctionalInterface marked out with (or may not be labeled, after all, only a function / method)

Why can only define a function interface it: because our lamda functions are common type of method, the compiler will automatically identify which method.

 

Example:

// This is the thread interfaces

@FunctionalInterface
    public interface Runnable { void run(); }

Can also declare multiple interfaces, but a default Object interface must be inherited (equals all classes inherit Object Interface), the interface can be displayed in lamda declare more than one function.

如下:
    public interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); }

 

According to interface types, the compiler automatically matching method. Including lamda custom interface, such as

@FunctionalInterface
    public interface MyRunnable {
        public void run();
    }

Under the wording are correct, automatically match the corresponding interface function

  Runnable r1 =    () -> {System.out.println("Hello Lambda!");};
    MyRunnable2 r2 = () -> {System.out.println("Hello Lambda!");};

This shows that a λ expression can have multiple target types (function interface), as long as the function can be successfully matched.

 

3 lamda expression uses

3.1 Internal anonymous class, all kinds of callbacks, such as incident response, a passing Runnable Thread class, etc.

Thread oldSchool = new Thread( new Runnable () {
        @Override
        public void run() {
            System.out.println("This is from an anonymous class.");
        }
    } );
   
    Thread gaoDuanDaQiShangDangCi = new Thread( () -> {
        System.out.println("This is from an anonymous method (lambda exp).");
    } );

The second is lamda expressions, the compiler will automatically inferred: a Thread constructor accepts a Runnable argument, the incoming λ expression fits its run () function, so the Java compiler infer it to Runnable

 

3.2  collections batch operation

3.2.1)list

Batch operation API collection class is to achieve "internal iteration" collection class (user wrote previously for Formula own loop iteration), and a desired full advantage of modern multi-core CPU parallel computation.

for (Object o: list) { // external iteration
        System.out.println (O);
    }

Can be written as:

    list.forEach (o -> {System.out.println (o);}); // forEach iteration function for internal

3.2.2) stream

 List<Shape> shapes = ...
    shapes.stream()
      .filter(s -> s.getColor() == BLUE)
      .forEach(s -> s.setColor(RED));

Predicate filter method parameters are type, parameter types Consumer forEach method is, they are a function of the interface, it is possible to use an expression λ

There is also a method called parallelStream (), as the name suggests it and stream (), in that it indicates to parallel processing, in order to take full advantage of modern multi-core CPU's characteristics.

The following is a typical large data processing method, Filter-Map-Reduce:

    // given array of type String, to identify where all distinct primes
    public void distinctPrimary (String ... Numbers) {
        List <String> L = Arrays.asList (Numbers);
        List <Integer> = R & lt L. Stream ()
                .map (E -> new new Integer (E))
                .filter (E -> Primes.isPrime (E))
                .distinct ()
                .collect (Collectors.toList ());
        System.out.println ( "distinctPrimary IS Result: "+ R & lt);
    }

You might think that in this case, List l is iterated many times, map, filter, distinct both are one cycle, the efficiency will be bad. It is not the case. The return another Stream methods are "lazy (lazy)", and the last to return the final result collect method is "anxious (eager)" is. Before meeting eager method, the method does not perform lazy.

3.2.3) Optional use

Optional itself to solve the problem java infamous null pointer, but with lamda expression, we made some very powerful features.

1)map

public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else {
        return Optional.ofNullable(mapper.apply(value));
    }
}

The parameter defines a function lamda objective function value Optional when empty, return empty.

Is not NULL, then the parameter T lamda value as the objective function, the return value returned in accordance with the actual parameter R

Join Opational call the following method:

map(StreamExecutionEnvironmentFactory::createExecutionEnvironment)

The actual value is empty. Empty site is called the method of lamda expression references StreamExecutionEnvironmentFactory.createExecutionEnvironment (value)

4 reference method

Any λ expression may represent a unique method descriptor anonymous function interface. We can also use a specific method of a class to represent the descriptors, called reference method

/ c1 and c2 are the same (static method reference)
    Comparator <Integer> c2 = (X, Y) -> Integer.compare (X, Y);
    Comparator <Integer> = C1 :: Compare Integer;

 // The following two are the same (reference example method. 1)
    persons.forEach (E -> System.out.println (E));
    persons.forEach (the System.out :: the println);

// The following two are the same (reference example method 2)
    persons.forEach (Person -> person.eat ());
    persons.forEach (the Person :: EAT);

 // The following two are the same (reference constructor)
    strList.stream () Map (S -> new new Integer (S));.
    . StrList.stream () Map (:: new new Integer);

 

Reference documents: https://blog.csdn.net/ioriogami/article/details/12782141

Published 16 original articles · won praise 0 · Views 2816

Guess you like

Origin blog.csdn.net/peidezhi/article/details/104049777