java8之Lambda表达式

基本用法

public class MyLambda1 {
	
	@Test
	public void test2() {
		//Arrays.asList( "a", "b", "d" ).forEach( ele -> System.out.println(ele));
		Arrays.asList( "a", "b", "d" ).forEach((String ele) -> {System.out.println(ele);});
	}
	
	@Test
	public void test3() {
		Arrays.asList( "a", "b", "d" ).forEach((String ele) -> {
			System.out.print("hello:");
			System.out.println(ele);
			}
		);
	}
	
	@Test
	//可以引用类的局部变量和成员变量, 会将局部变量和成员变量隐式转换为final
	public void test4() {
		/*final*/ String say = "say:";
		Arrays.asList( "a", "b", "d" ).forEach((String ele) -> {
			System.out.print(say);
			System.out.println(ele);
			}
		);
	}
	
	// lambda表达式有返回值,如果语句只有一条,可以不显示使用return,返回值类型编译器会自动推断
	@Test
	public void test5() {
		Arrays.asList( "a", "b", "d" ).sort((String ele1, String ele2) -> ele1.compareTo(ele2));
		/*Arrays.asList( "a", "b", "d" ).sort((String ele1, String ele2) ->{ 
			int code = ele1.compareTo(ele2);
			return code;
			}
		);*/
	}
	
	//函数接口:只有一个函数的额接口,这样的接口可以隐式的转换为Lambda表达式
	//java.lang.Runnable和java.util.concurrent.Callable是函数式接口的最佳例子
	//@FunctionalInterface可以让限制接口只有一个函数(不包括默认方法和静态方法)
	@Test
	public void test1() {
		MathOpreation mathOpreation = (int a, int b) -> {return a + b;};
		System.out.println(mathOpreation.operation(1, 2));
	}
	
	@FunctionalInterface
	public interface MathOpreation {
		int operation(int a, int b);
		
		default int minus(int a, int b) {
			return a - b;
		}
		
		static void say(String content) {
			System.out.println("say:" + content);
		}
	}

}

你可能感兴趣的:(java8)