lambada Expressions for Deep and Simple Functional Programming

Keywords: Lambda JDK Programming

lambda is a new feature of JDK 1.8. Functional programming can not be ignored. See:

lambda underlying implementation principle

1. The compiler generates a method for each lambda expression
		The method name is lambda lambda $0,1,2,3,,1,2,3, but the expression referenced by the method does not generate the method.
2. An invokeDynamic instruction is generated at lambda, which is called
		Bootstrap method, bootstrap method will point to the automatically generated lambda lambda $0
		Method or method references.
3. The bootstrap method uses a static method called LambdaMetafactory.metafactory
		This method returns to CallSite, which contains Method Handle.
		That is, the method that is ultimately invoked.
4. Boot methods are called only once.
Method of automatic generation:
5. Input and output are consistent with lambda
 6. If this is not used, then it is the static method, otherwise it is the member method.

Example:

public strictfp class LambdaDemo1 {
	public static void main(String[] args) {
		//Reference Interface 1 to Implement i*2
		Interface1 i1 = (i) -> i * 2;
		//Reference Interface 1 to Realize 10-3
		Interface1.sub(10, 3);
		//First add and then multiply.
		System.out.println(i1.add(3, 7));
		System.out.println(i1.doubleNum(20));
		//Reference interface 2i*2
		Interface2 i2 = i -> i * 2;
		//Multiply 2 and print
        System.out.println("i2:"+i2.doubleNum(333333333));
		//Reference interface 3i*3
        Interface3 i5 = i -> i*3;
        //Multiply 3 and print
        System.out.println("i5:"+i5.doubleNum(333333333));
		//Reference Interface 1 Prints First - - - Then i*2
		Interface1 i4 = (int i) -> {
			System.out.println("-----");
			return i * 2;
		};
		//Multiply 2 and print out
        System.out.println(i4.doubleNum(100));
	}
	
	@FunctionalInterface
	interface Interface1 {
		int doubleNum(int i);
	
		default int add(int x, int y) {
			return x + y;
		}
	
	static int sub(int x, int y) {
		return x - y;
	}
}

	@FunctionalInterface
	interface Interface2 {
		int doubleNum(int i);
	
		default int add(int x, int y) {
			return x + y;
		}
	}
	
	@FunctionalInterface
	interface Interface3 extends Interface2, Interface1 {
		@Override
		//inherit
		default int add(int x, int y) {
			return Interface1.super.add(x, y);
		}
	}
}

Posted by Darkness Soul on Tue, 08 Oct 2019 20:50:43 -0700