"Java 8 Combat" (ii)--LAMDA

Source: Internet
Author: User

A LAMDA expression can be understood as a way to succinctly represent an anonymous function that can be passed: it has no name, but it has a parameter list/function body/return type, and there may be a list of exceptions that can be thrown.

The LAMDA expression consists of a parameter/arrow and a body :

(Apple A1, Apple A2)  A1.getweight (). CompareTo (A2.getweight ());

The previous code form:

comparator<apple> byweight = new Comparator<apple> () {
public int Compare (Apple A1, Apple A2) {

Return A1.getweight (). CompareTo (A2.getweight ());

}

}

Lamda expressions that are valid in Java 8:

1, (String s), S.length ()

has a parameter of type string and returns an int. The LAMDA expression does not have a return statement because the return is already implied.

2, (Apple a), A.getweight () > 150

The parameter is the Apple type and returns a Boolean type.

3, (int x, int y), {

System.out.println ("Result");

System.out.println (X+y);

}

The LAMDA expression has two arguments of type int without a return value. Lamda expressions can contain multiple lines of statements.

() {return "Mario";}

The LAMDA expression is also valid.

4, ()-> 42

The LAMDA expression has no arguments and returns an int

5, (Apple A1, Apple A2), A1.getweight (). CompareTo (A2.getweight ())

The expression has two Apple-type parameters and returns an int

invalid LAMDA expression :

(Integer i), return "Alan" + i;

(String s), {"Ironman";}

In the first expression, return is a control flow statement. To make this statement valid, you need to add curly braces.

In the second expression, "Ironman" is an expression, not a statement. To make this lamda effective, you can remove curly braces and semicolons.

LAMDA Basic Syntax :

(parameters), expression

Or

(parameters), {statements;}

Where Lamda expressions can be used-functional interfaces

A functional interface is an interface that defines only an abstract method. such as comparator and runnable interfaces.

The LAMDA expression can be directly inline to provide the implementation of the abstract method of the functional interface, and the entire expression as an instance of the functional interface.

The signature of an abstract method of a functional interface is the signature of an LAMDA expression. This abstract method is called a function descriptor.

In the new Java API, the functional interface has @functionalinterface annotations. If an interface is defined with @functionalinterface, but it is not a functional interface, it will return an error indicating the cause, such as "multiple non-overriding abstract methods found in Interface Foo "indicates that there are multiple abstract methods.

to use the LAMDA expression :

1, the behavior of parameterization:

Extract Lamda expressions, design parameters, function bodies and return values.

2, use the function interface to pass the behavior:

Create a functional interface I that matches the LAMDA expression and pass this interface as an argument to the function m that needs to use the LAMDA expression.

3, perform the behavior in the function interface

Invoking the abstract function in the interface I in function m

4, passing LAMDA expression

Common functional Interfaces:

Pre-existing Java 8 functional interfaces:

Comparable

Runnable

Callable

The new functional interface introduced in Java 8 in the Java.util.function package:

 predicate 

@FunctionalInterface Public InterfacePredicate<t>{    BooleanTest (T T);} Public Static<T> list<t> Filter (list<t> List, predicate<t>p) {List<T> results =NewArraylist<>();  for(T s:list) {if(P.test (s)) {Results.add (s); }    }    returnresults;} predicate<String> nonemptystringpredicate = (String s)!S.isempty (); List<String> nonempty = Filter (listofstrings, nonemptystringpredicate);

  Consumer  

  

@FunctionalInterface  Public Interface Consumer<t>{    void  accept (T-T);}  Public Static void ForEach (list<t> List, consumer<t> c) {        for(T i:list) {        c.accept (i);    }} ForEach (Arrays.aslist (1,2,3,4,5), (Integer i), System.out.println (i));

  Function

@FunctionalInterface  Public Interface Function<t, r>{    R apply (T t);}  Public static <t, r> list<r> map (list<t> list,function<t, r> f) {    Listnew< /c10> arraylist<>();      for (T s:list) {        Result.add (f.apply (s));    }     return result;} List<Integer> L = map (arrays.aslist ("Lambdas", "in", "Action"), (String s), s.length ());

LAMDA and functional Interface examples

Use case Examples of Lambda The corresponding function-type interface
Boolean expression (list<string> List), List.isEmpty () Predicate<list<string>>
Creating objects ()-New Apple (10) Supplier<apple>
Consume an Object (Apple a), System.out.println (A.getweight ())

The lambda example corresponds to a function-type interface

                     

Consume an object (Apple a)
System.out.println (A.getweight ())
Consumer<apple>
From an object
Select/extract
(String s) s.length () function<string, integer> or
Tointfunction<string>
Merge two values (int a, int b), A * b intbinaryoperator
Compare two objects (Apple A1, Apple A2)
A1.getweight (). CompareTo (A2.getweight ())
Comparator<apple> or
Bifunction<apple, Apple, integer>
or Tointbifunction<apple, apple>

"Java 8 Combat" (ii)--LAMDA

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.