java lambda 学习笔记

来源:互联网 发布:淘宝秒杀店铺 编辑:程序博客网 时间:2024/05/16 07:57
今天刚刚参加完oracle举办的java沙龙,java的现在与未来。

1.外迭代与内迭代

外迭代例子:

List<Student> students = ...double highestScore = 0.0;for (Student s : students) {if (s.gradYear == 2011) {if (s.score > highestScore) {highestScore = s.score;}}}

例子是串行运行的会从头到尾的运行,而且线程是不安全的。

内迭代例子:

List<Student> students = ...double highestScore = students.filter(new Predicate<Student>() {public boolean op(Student s) {return s.getGradYear() == 2011;}}).map(new Mapper<Student,Double>() {public Double extract(Student s) {return s.getScore();}}).max();

例子是并行运行的,而且线程是安全的。

使用了lambda的内迭代例子:

SomeList<Student> students = ...double highestScore = students.filter(Student s -> s.getGradYear() == 2011).map(Student s -> s.getScore()).max();

使用了lambda表达式提高了代码的可读行,同时可以降低出错的可能性,对并行也有更好的支持。


2.类型推理

编译器通常可以推断lambda表达式的参数类型

static void sort(List<T> l, Comparator<? super T> c);

Collections类的sort可以通过自定义的Comparator来排序

使用lambda表达式的例子:

List<String> list = getList();Collections.sort(list, (String x, String y) -> x.length() - y.length());

因为编译器支持推断lambda表达式的参数类型,所以可以改写成

Collections.sort(list, (x, y) -> x.length() - y.length());
这样处理的优点是完全静态类型,提供对嵌入式的支持。

0 0
原创粉丝点击