Lambda简介
Lambda 表达式是 JDK8 的一个新特性,可以取代大部分的匿名内部类,写出更优雅的 Java 代码,尤其在集合的遍历和其他集合操作中,可以极大地优化代码结构。
JDK 也提供了大量的内置函数式接口供我们使用,使得 Lambda 表达式的运用更加方便、高效。
@Data
@NoArgsConstructor
@AllArgsConstructor
static class Temp {
private String name;
private Integer age;
}
1.删除集合中的某个元素
一般来说,List删除对应的数据需要自己手动的使用Iterator去对应,然后删除元素,现在removeIf这个方法就已经帮我们封装好了。
源码:
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
我们现在只需要这样就能实现删除操作,一步完成,完美
List<Temp> temps = new ArrayList<>();
temps.add(new Temp("Tom",1));
temps.add(new Temp("Jack",20));
temps.add(new Temp("Mary",5));
temps.add(new Temp("Nick",100));
temps.add(new Temp("Sun",10));
temps.add(new Temp("Jerry",0));
temps.removeIf(e-> Objects.equals(e.getAge(),1));
temps.forEach(System.out::println);
2.然后是排序功能,之前我们都是需要实体类实现Comparable接口,重写CompareTo()方法或者调用 sort 方法,传入比较器匿名内部类重写 compare 方法等,现在又有封装好的了
源码:
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor)
{
Objects.requireNonNull(keyExtractor);
return (Comparator<T> & Serializable)
(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}
我们如何实现呢
List<Temp> temps = new ArrayList<>();
temps.add(new Temp("Tom",1));
temps.add(new Temp("Jack",20));
temps.add(new Temp("Mary",5));
temps.add(new Temp("Nick",100));
temps.add(new Temp("Sun",10));
temps.add(new Temp("Jerry",0));
temps.sort((Comparator.comparing(Temp::getAge)));
temps.forEach(System.out::println);
ps:上面的排序是升序的,那我们怎么降序呢
temps.sort((Comparator.comparing(Temp::getAge)).reversed());
这样就好了