一、函数式接口
1、Function函数式接口:有一个输入参数,有一个输出
2、断定型接口:有一个输入参数,返回值只能是布尔值!
3、Consumer 消费型接口:只有输入,没有返回值
4、Supplier供给型接口:没有参数,只有返回值
二、常用的Lambda写法
1、如果model不为空,获取他的data属性,否则返回null
Optional.ofNullable(model).map(Record::getData).orElse(null);
2、遍历list,获取每一个对象的name属性,转化为list返回
.stream().map(Type::name).collect(Collectors.toList());
3、2的并行处理
.parallelStream().filter(Objects::nonNull).map(Model::getName()).collect(Collectors.toList());
4、guava创建集合
Lists.newArrayList()
Maps.newHashMap();
5、遍历apps,获取每个元素的hex属性,mapToLong转化为LongStream,最后求和,intValue向下转型为int
Long.valueOf(apps.stream().mapToLong(Type::getHex).sum()).intValue();
6、list不为空,转化为userId list,并且去重
Optional.ofNullable(repayProps).orElse(Lists.newArrayList()).stream().map(FlowProps::getUserId).distinct().collect(Collectors.toList());
7、list中获取第一个元素findFirst
Model model = list.stream().findFirst().orElse(null);
8、把各个元素相加得出一个结果
List<BigDecimal> bigDecimals = new ArrayList<>();
bigDecimals.add(new BigDecimal("1"));
bigDecimals.add(new BigDecimal("2"));
BigDecimal bigDecimal = bigDecimals.stream().reduce(new BigDecimal(100),BigDecimal::add);
System.out.println(bigDecimal);// 103
9、求最小值
Model model = list.stream().min(Comparator.comparing(Model::getId)).orElse(null);
10、分组
Map<Long, List<Model>> map = list.stream().collect(Collectors.groupingBy(Model::getId));
11、是否有任意一个符合
List<String> names = Arrays.asList("11","22", "33");
System.out.println(names.stream().anyMatch("3"::startsWith));// false
System.out.println(names.stream().anyMatch("333"::startsWith));// true
12、抛异常
.stream().findFirst().orElseThrow(() -> new IllegalArgumentException("no available"))
13、排序
.stream().sorted(Comparator.comparingInt(VO::getTerms)).collect(Collectors.toList());
14、逆序
.stream().sorted(Comparator.comparingInt(VO::getIndex).reversed()).collect(Collectors.toList());
15、转为map
Map<Long, VO> vOMap = vOs.stream().collect(Collectors.toMap(vo -> vo.id, vo -> vo));
vOs.stream().collect(Collectors.toMap(VO::getId, Function.identity()));
16、 flatMap 是一个 map 和一个 flat 操作的组合。其首先将一个函数应用于元素,然后将其展平,当你需要将 [[a,b,c],[d,e,f],[x,y,z]] 具有两个级别的数据结构转换为 [a,b,c,d,e,f,x,y,z] 这样单层的数据结构时,就选择使用 flatMap 处理。如果是 [a,b,c,d,e,f,x,y,z] 转换为大写 [A,B,C,D,E,F,X,Y,Z] 这样单层转换,就使用 map 即可
List<Son> sonList = fatherS.stream().map(Father::getSons).flatMap(Collection::stream).collect(Collectors.toList());
17、遍历
.stream().forEach(x -> x.setCode(code));
18、计数
.stream().count();
19、逗号分隔
.collect(Collectors.joining(","));
20、去重
.distinct()
21、获取任意一个,类似findFirst
.stream().findAny().get().getOrderId();
22、如果当前值存在,传入一个Consumer
.ifPresent(info -> {System.out.println(info)});
23、如果存在值则返回true,否则返回false
.isPresent()
24、转为set
.collect(Collectors.toSet());
25、返回此流中是否没有元素与所提供的predicate函数匹配
// vOs列表中没有任何一个元素的ID包含在ids列表中
vOs.stream().noneMatch(vo -> ids.contains(vo.getId()))