lambda表达式:
1.形式:参数,箭头(->)以及一个表达式
eg:(String first,String second)->{
if(first.length() < second.length()) return -1;
else if(first.length() > second.length()) return 1;
return 0;
}
2.lambda表达式可以没有参数,就想无参函数一样:
()->{
for(int i = 100;i >= 0;i--)
System.out.println(i);
}
3.如果可以推导出一个lambda表达式的参数类型,可以忽略其类型。
eg:Comparator(String) comp = (first,second)->first.length() - second.length() //就像(String first,String second)->first.length() - second.length()一样
4.无需指定lambda表达式的类型,lambda表达式的返回类型总是会由上下文推导得到,如上例。
注:如果lambda表达式值在某些分支返回一个值,而在另外的一些分支不返回值,是不合法的
eg:(int x )->{if(x > 0) return 1;}
测试程序:
package com.lw.lambdaDemo;
import java.util.Arrays;
public class LambdaDemo {
public static void main(String[] args) {
String[] planets = new String[]{"Mercuy","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"};
System.out.println(Arrays.toString(planets));
System.out.println("Sorted in dictionary order:");
Arrays.sort(planets);
System.out.println(Arrays.toString(planets));
System.out.println("Sort by length:");
Arrays.sort(planets, (first ,second)->first.length() - second.length());
System.out.println(Arrays.toString(planets));
}
}
输出结果是:
[Mercuy, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune]
Sorted in dictionary order:
[Earth, Jupiter, Mars, Mercuy, Neptune, Saturn, Uranus, Venus]
Sort by length:
[Mars, Earth, Venus, Mercuy, Saturn, Uranus, Jupiter, Neptune]