当前位置: 移动技术网 > IT编程>开发语言>Java > Java 8 Lambda表达式基础语法

Java 8 Lambda表达式基础语法

2020年07月12日  | 移动技术网IT编程  | 我要评论
/**
 * 
 * 一、Lambda 表达式的基础语法:
 * Java8中引入了要给新的操作符 “->” 该操作符称作箭头操作符 或 Lambda操作符
 * 箭头操作符将Lambda拆分成两部分: 
 * 左侧:Lambda表达式参数列表(对应函数接口中抽象方法的参数列表)
 * 右侧:Lambda表达式中所需要执行的功能,即Lambda体(对应函数接口中抽象方法实现的功能) Lambda可以看作对函数接口的实现。
 * 
 * 根据函数接口抽象方法的情况 
 * 语法格式一:无参数,无返回值 
 * 			 () -> System.out.println("Hello Lambda!");
 * 
 * 语法格式二:有一个参数,无返回值 
 *  		 (t) -> System.out.println(t);
 * 
 * 语法格式三:若只有一个参数,小括号可以省略不写 
 *            t -> System.out.println(t);
 *
 * 语法格式四:有两个以上的参数,有返回值,并且Lambda体中有多条语句
 *		Comparator<Integer> com = (x, y) -> {
 *			System.out.println("函数式接口");
 *			return Integer.compare(x, y);
 *		};
 *
 * 语法格式五:若Lambda中只有一条语句,return和大括号都可以省略不写 
 * 		Comparator<Integer> com = (x,y) -> Integer.compare(x, y);
 * 
 * 语法格式六:Lambda的参数列表数据类型可以省略不写,因为JVM编译器可以根据上下文推断出,数据类型,即“类型推断”
 * 
 * 总结: 
 * 上联:左右遇一括号省 
 * 下联:左侧推断类型省 
 * 横批:能省则省
 * 
 * 二、Lambda表达式需要“函数式接口”的支持 
 * 函数式接口:
 * 接口中只有一个抽象方法的接口,称为函数式接口。可以使用注解@FunctionInterfa修饰 :可以检查是否是函数式接口。
 */
public class TestLambda2 {

	@Test
	public void test1() {
		int num = 0;// jdk7 之前,必须写final

		Runnable r = new Runnable() {
			@Override
			public void run() {
				System.out.println("hello world!" + num);
			}
		};
		new Thread(r).start();

		Runnable r1 = () -> System.out.println("hello lambda!" + num);
		new Thread(r1).start();
	}

	@Test
	public void test2() {
		Consumer<String> con = (t) -> System.out.println(t);
		con.accept("java nb");
	}

	@Test
	public void test3() {
		Comparator<Integer> com = (x, y) -> {
			System.out.println("函数式接口");
			return Integer.compare(x, y);
		};
	}

	@Test
	public void test4() {
		Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
	}

	// 需求;对一个数进行运算
	@Test
	public void test5() {
		Integer num1 = operation(100, x -> x++);
		Integer num2 = operation(100, x -> x*x);
		System.out.println(num1 + "---" + num2);
	}

	public Integer operation(Integer num, MyFun fun) {
		return fun.getValue(num);
	}

}
@FunctionalInterface
public interface MyFun {
	
	public Integer getValue(Integer num);
	
}

 

本文地址:https://blog.csdn.net/AhaQianxun/article/details/107272448

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网