标签:大括号 参数 [] rri pareto 自动 compareto 一行代码 变量
Lambda表达式是Java 8中最大和最令人期待的特性。Lambda表达式促进函数式编程,并大大简化了开发过程。
Lambda表达式使用 -> 语法
parameter -> expression body
(Type1 param1, Type2 param2, ..., TypeN paramN) -> { statment1; statment2; //............. return statmentM; }
下面是lambda表达式的重要特征—
public class Java8Tester { public static void main(String args[]){ Java8Tester tester = new Java8Tester(); //with type declaration MathOperation addition = (int a, int b) -> a + b; //with out type declaration MathOperation subtraction = (a, b) -> a - b; //with return statement along with curly braces MathOperation multiplication = (int a, int b) -> { return a * b; }; //without return statement and without curly braces MathOperation division = (int a, int b) -> a / b; System.out.println("10 + 5 = " + tester.operate(10, 5, addition)); System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction)); System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication)); System.out.println("10 / 5 = " + tester.operate(10, 5, division)); //without parenthesis GreetingService greetService1 = message -> System.out.println("Hello " + message); //with parenthesis GreetingService greetService2 = (message) -> System.out.println("Hello " + message); greetService1.sayMessage("Mahesh"); greetService2.sayMessage("Suresh"); } interface MathOperation { int operation(int a, int b); } interface GreetingService { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation){ return mathOperation.operation(a, b); } }
你可以直接访问标记了final的外层局部变量,或者实例的字段以及静态变量()。 Lambda表达式可以引用类成员和局部变量(会将这些变量隐式得转换成final的),如下列中的separator默认是final。
String separator = ","; Arrays.asList( "a", "b", "d" ).forEach( ( String e ) -> System.out.print( e + separator ) );
在老版本中,只需要给静态方法 Collections.sort 传入一个List对象以及一个比较器来按指定顺序排列。通常做法都是创建一个匿名的比较器对象然后将其传递给sort方法。
List<String> names = Arrays.asList("peter", "anna", "mike", "xenia"); Collections.sort(names, new Comparator<String>() { @Override public int compare(String a, String b) { return b.compareTo(a); } });
使用lambda表达式:
Collections.sort(names, (String a, String b) -> { return b.compareTo(a); });
函数体只有一行代码,可以去掉大括号和return:
Collections.sort(names, (String a, String b) -> b.compareTo(a));
不写参数类型,有Java编译器自动推导:
Collections.sort(names, (a, b) -> b.compareTo(a));
标签:大括号 参数 [] rri pareto 自动 compareto 一行代码 变量
原文地址:http://www.cnblogs.com/april-chen/p/7228181.html