Java语法糖写法

发布于:2024-06-20 ⋅ 阅读:(102) ⋅ 点赞:(0)

一、函数式接口

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

.stream().filter(s -> s.getType() == fileType).findFirst().orElse(null);

8、把各个元素相加得出一个结果

.stream().reduce(BigDecimalHelper::addWithNullAsZeroAndScale).orElse(BigDecimal.ZERO)
.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

9、求最小值

.stream().min(Comparator.comparing(Record::getIndex));

10、分组

.stream().collect(Collectors.groupingBy(vo -> vo.getType().name() + vo.getDate()));

11、是否有任意一个符合

Collection<String> prefixList
String userChannel
prefixList.stream().anyMatch(userChannel::startsWith);

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

.stream().collect(Collectors.toMap(Record::getId, v -> v));

16、flatMap返回Stream,还可以继续.

.stream().flatMap(Collection::stream).filter(Objects::nonNull).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());

网站公告

今日签到

点亮在社区的每一天
去签到