jdk8 new features -Lambda expression

Summary

Lambda allowed to function as an argument of a method (function as a parameter passed into the process). Can replace most anonymous inner classes, Java code written more elegant, in particular through the collection and the other set operations, can greatly optimize the code structure.

Basic grammar

(parameters) -> expression
(parameter1,parameter2) ->{ statements; }

1. No reference None Return Value

// no-argument no return

/**无参无返回值*/
@FunctionalInterface
public interface NoReturnNoParamMethod {
	void operate();
}
NoReturnNoParamMethod noReturnNoParamMethod = () -> {
    System.out.println("无参无返回");
};
noReturnNoParamMethod.operate();

2. a parameter None Return Value

/**一个参数无返回*/
@FunctionalInterface
public interface NoReturnOneParamMethod {
    void operate(int a);
}
//一个参数无返回
NoReturnOneParamMethod noReturnOneParamMethod = a-> {
    System.out.println("一个参数无返回 param:" + a);
};
noReturnOneParamMethod.operate(6);

3. The multi-parameter None Return Value

/**多参数无返回*/
@FunctionalInterface
public interface NoReturnMultiParamMethod {
    void operate(int a, int b);
}
//多个参数无返回
NoReturnMultiParamMethod noReturnMultiParamMethod = (a, b) -> {
    System.out.println("多个参数无返回 param:" + "{" + a +"," + + b +"}");
};
noReturnMultiParamMethod.operate(6, 8);

4. No parameter returns a value

/*** 无参有返回*/
@FunctionalInterface
public interface ReturnNoParamMethod {
    int operate();
}
//无参有返回值
ReturnNoParamMethod returnNoParamMethod = () -> {
    System.out.print("无参有返回值");
    return 1;
};
int res = returnNoParamMethod.operate();
System.out.println("return:" + res);

The parameter has a return value

/**一个参数有返回值*/
@FunctionalInterface
public interface ReturnOneParamMethod {
    int operate(int a);
}
//一个参数有返回值
ReturnOneParamMethod returnOneParamMethod = a -> {
    System.out.println("一个参数有返回值 param:" + a);
    return 1;
};
int res2 = returnOneParamMethod.operate(6);
System.out.println("return:" + res2);

6. A plurality of return value parameters

/**多个参数有返回值*/
@FunctionalInterface
public interface ReturnMultiParamMethod {
    int operate(int a, int b);
}
//多个参数有返回值
ReturnMultiParamMethod returnMultiParamMethod = (a, b) -> {
    System.out.println("多个参数有返回值 param:" + "{" + a + "," + b +"}");
    return 1;
};
int res3 = returnMultiParamMethod.operate(6, 8);
System.out.println("return:" + res3);

Reference Methods

:: attribution method by method name belonger static method for the class name, common ownership by targeting method

public static void main(String args[]){
    List<String> names = new ArrayList();
    names.add("小杨");
    names.add("小张");
    names.add("小红");
    names.add("小王");
    names.forEach(System.out::println);
}

Export

Xiao Yang
Xiao Zhang
Xiao Hong
Wang

Published 43 original articles · won praise 28 · views 50000 +

Guess you like

Origin blog.csdn.net/u014395955/article/details/104042599