JAVA8特性 stream()流各种操作

JAVA8特性 stream()流各种操作

什么是 Stream?是一个来自数据源的元素队列并支持聚合操作。在项目开发过程中经常使用排序、过滤、转换和一些操作,使用流可以使得代码简洁易读,说到底就是懒得写那么多for筛选和组装。

1.最大最小值比较

List<BigDecimal> list = new ArrayList<>(Arrays.asList(new BigDecimal("1.23"), new BigDecimal("1.24")));
BigDecimal max = list.stream().max(Comparator.comparing(m -> m)).orElse(null);
BigDecimal min = list.stream().min(Comparator.comparing(m -> m)).orElse(null);
System.out.println(min);
System.out.println(max);

2.列表平方数处理

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
List<Integer> squaresList = numbers.stream().map( i -> i*i).collect(Collectors.toList());
System.out.println(squaresList);

3.实体类某字段排序(降序)

T为使用的实体类,getCount为实体类属性count的get方法,降序就加入reversed(),升序就把reversed()删除(下面使用到的大致相同就不解释了)

List<T> resList = list.stream().sorted(Comparator.comparing(T::getCount).reversed()).collect(Collectors.toList());

4.实体类某字段空值过滤

List<String> collect = list.stream().filter(e -> e.getId() != null).map(T::getId).collect(Collectors.toList());

5.实体类两个字段排序(首先排分数,再排评论数)

List<T> sortByScoreAndCommentList = data.stream().sorted(Comparator.comparing(T::getScore, Comparator.reverseOrder())
        .thenComparing(T::getCommentCount, Comparator.reverseOrder())).collect(Collectors.toList());

6.根据实体类某类型分组

Map<String, List<T>> mapByType = list.stream().collect(Collectors.groupingBy(T::getType));

7.根据实体类某两个字段组合(例如编号和名字)

Map<Long, String> map = list.stream().collect(Collectors.toMap(T::getId, T::getName));

8.拼接实体类某字段

String collect = list.stream().filter(r -> r.getName() != null).map(T::getName).collect(Collectors.joining(","));

另外还有一些.distinct()去重、.limit(10)指定数量、parallelStream() 并行流等等后面使用到再总结吧!


9.根据实体类编号转成Map<Integer, T>形式

有时候处理一下列表数据,树结构或者多级拼接展示,需要不断查询数据进行拼接。如果能获取一次数据库数据后,就不需要for循环一次次查询了,所以根据主键分组取出数据就可以根据子级和父级进行处理。

 Map<Integer, T> map = list.stream().collect(Collectors.groupingBy(T::getId,Collectors.collectingAndThen(Collectors.toList(),value->value.get(0))));

10.根据实体类逗号分隔存储的int数据转List(20230222)

List<Integer> collect = Arrays.stream([实体类].[String类型逗号分隔属性].split(",")).map(Integer::parseInt).collect(Collectors.toList());

11.根据List<Map<String,Object>>获取key值或者value值

//String类型的key值去重获取
List<String> collect = list.stream().flatMap(map -> map.keySet().stream()).distinct().collect(Collectors.toList());
//获取map中value值
List<String> collect = list.stream().filter(map -> map.containsKey("[map的key值]")).map(map -> (String) map.get("[map的key值]")).collect(Collectors.toList());

12.String列表拼接(逗号)成字符串(20230413)

String result = list.stream().collect(Collectors.joining(","));
String result = String.join(",", list);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值