Lamda
规则:
接口必须是函数式接口---@FunctionalInterface
接口里面只能够存在一个抽象方法
java8还有个特性就是如果你的接口中没有抽象方法,但有个默认(default)方法,它也是函数式接口
语法:
- - 简写模式: (参数列表)-> 方法主体
- -无参模式: () -> 方法主体
- - 非简写模式:(参数列表)-> {方法主体;}
Stream
三步骤:创建流 - 中间操作 - 最终操作
创建流
流的创建有两种方式。
如果是集合的话,可以直接使用 stream() 方法创建流,因为该方法已经添加到 Collection 接口中。
如果是数组的话,可以使用 Arrays.stream() 或者 Stream.of() 创建流;
1 | public static void test1() { |
中间操作
- filter (过滤)
- map (映射)
- sorted (排序)
- distinct (去重)
- limit / skip (限制)
filter (过滤)
根据判断条件过滤元素
1 | List<UserDO> resultList = userList.stream() |
map (映射)
映射每个元素到对应的方法
1 | List<String> bs = Arrays.asList("bb","cc","dd","cc"); |
结果:
map= = = = = = =
bb未知数
cc未知数
dd未知数
cc未知数
sorted (排序)
按条件进行排序
1 | List<Integer> ls = new ArrayList<Integer>(); |
结果:
sorted= = = = = = = = = =
1
3
5
distinct (去重)
去除集合或者数组中重复得数据
1 | Stream<String> s3 = Stream.of("aa","bb","cc" ,"cc"); |
结果:
aa
bb
cc
limit/skip
limit 返回 Stream 的前面 n 个元素;
skip 则是扔掉前 n 个元素。
limit
1 | List<Integer> ls = new ArrayList<Integer>(); |
结果:
limit = = = = = = = = = =
3
skip
1 | List<Integer> ls = new ArrayList<Integer>(); |
结果
skip= = = = = = = = = =
5
1
最终操作
匹配
- anyMatch() - - 根据条件返回是否有匹配的结果
- allMatch() – 只要有一个元素不匹配传入的条件,就返回 false;如果全部匹配,则返回true。
- noneMatch() – 只要有一个元素匹配传入的条件,就返回 false;如果全部不匹配,则返回 true。
组合
- reduce() - -把元素组合起来
计数
- count()
- max()
- min()
迭代
- forEach()
汇总
- collect() –将流中的元素汇总
匹配
1 | boolean isFound = userList.stream() .anyMatch(user -> Objects.equals(user.getId(), userId)); |
组合
1 | List<Integer> nums = Arrays.asList(1, 2, 5, 4); |
结果:22
小唠嗑:
本章到这里就结束了,谢谢耐心看到这里的各位Boss,如果觉得有哪里说的不好的地方,还请高抬贵手多多原谅,不惜指教。
最后,谢谢!