新特性的作用:简化代码,提高开发效率,性能是否有提高,目前没做测试。
Demo:
interface类:
package lambdaDemo;
@FunctionalInterface
public interface LambdaInterface {
int sum(int i,int j);
}
User类:
package lambdaDemo;
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Demo类:
package lambdaDemo;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
public class LambdaDemo {
public static void main(String[] args) {
//1.lamdba用于匿名类的实现
//老的方式
LambdaInterface oldWay = new LambdaInterface() {
@Override
public int sum(int i, int j) {
return i + j;
}
};
//新的方式
LambdaInterface newWay = (a,b) ->a+b;
System.out.println(oldWay.sum(2, 3));
System.out.println(newWay.sum(2, 3));
//2.lambda表达式用于集合的遍历
String[] x = {"赵","钱","孙","李","周","吴","郑","王","冯"};
String[] y = {"伯","仲","叔","季","甲","乙","丙","丁","三"};
List<User> userList = new ArrayList<User>();
for(int i = 0;i < 15;i++) {
String name = x[new Random().nextInt(x.length)] + y[new Random().nextInt(y.length)];
int age = new Random().nextInt(30);
User user = new User();
user.setName(name);
user.setAge(age);
userList.add(user);
}
List<String> nameList = userList.stream().map(user -> user.getName()).collect(Collectors.toList());
nameList.stream().forEach(s->{System.out.println(s);});
}
}
运行结果:
5
5
王仲
李甲
吴乙
赵甲
冯甲
赵季
王伯
郑叔
吴丙
王季
冯仲
郑甲
钱季
冯三
周三
总结:在做匿名实现时大大简化了代码,对集合的操作也非常简便。