Lambda的作用
- 避免匿名内部类定义过多
- 让代码更简洁
- 去除没有意义的代码,留下核心逻辑
函数式接口
- 任何接口,如果只包含了一个抽象方法,那么就是一个函数式接口
- 对于函数式接口,我们可以通过Lambda表达式来创建该接口的对象
Lambda表达式只能有一行代码的情况下可以简化,多行需要用代码块包裹
Lambda过滤
// 去除不存在用户
list = list.stream().filter(c -> c.getUser() != null).collect(Collectors.toList());
排序
// 流排序(升序)
articles.stream().sorted(Comparator.comparing(Article::getTitle)).collect(Collectors.toList())
// 流排序(降序)
articles.stream().sorted(Comparator.comparing(Article::getTitle).reversed()).collect(Collectors.toList())
// list排序
list.sort(Comparator.comparingInt(CommonType::getSortHot).reversed());
去重
// 去重
ArrayList<ClassAmountVo> collect = classExitsList.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ClassAmountVo::getClassId))),
ArrayList::new
)
);
// 字符去重
list=list.stream().distinct().collect(Collectors.toList());
获取某字段集合
List<String> collect = categoryList.stream().map(Category::getId).collect(Collectors.toList());