JDK 1.8 Lambda表达式集合分组条件过滤组装去重排序转换求和最值
Posted 每天译点晓知识
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDK 1.8 Lambda表达式集合分组条件过滤组装去重排序转换求和最值相关的知识,希望对你有一定的参考价值。
在jdk1.8中lambda表达式提供了集合的一些很实用的操作方法,函数式编程既减少了很多繁杂的foreach代码,又简洁明了,通俗易懂。
@Data
public class User
private String userId;
private String username;
private String nickName;
private String password;
private String picPath;
private String status;
private String sessionId;
private Date createTime;
private Date updateTime;
private int age;
private BigDecimal memberNum;
@Override
public String toString()
return "User [userId=" + userId + ", username=" + username
+ ", nickName=" + nickName + ", password=" + password
+ ", picPath=" + picPath + ", status=" + status
+ ", sessionId=" + sessionId + ", createTime=" + createTime
+ ", updateTime=" + updateTime + ", age=" + age + "]";
在创建上述对象的前提下(List<User> userList不为空):
1、通过指定字段分组Collectors.groupingBy().
Map<String, List<User>> groupByStatus = userList.stream().collect(Collectors.groupingBy(User::getStatus));
for (Map.Entry<String, List<User>> entry : groupByStatus.entrySet())
String status = entry.getKey();
List<User> userList = entry.getValue();
2、通过条件过滤filter().
List<User> userListByStatus = userList.stream().filter(t -> t.getStatus().equals("100")).collect(Collectors.toList());
3、获取list某个字段组装新list.
List<Long> userIdList = userList.stream().map(t -> t.getUserId()).collect(Collectors.toList());
4、去重distinct().
List<Long> userIdList = userList.stream().distinct().collect(Collectors.toList());
5、单字段多字段排序sort().
userList.sort(Comparator.comparing(User::getUserId));
userList.sort(Comparator.comparing(User::getUserId).thenComparing(User::getStatus));
注:若选择排序字段为null值,正序可userList.sort(Comparator.comparing(User::getUserId,Comparator.nullsFirst(Comparator.naturalOrder())))
6、list转map.
Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, t -> t,(k1,k2)->k1));
(其中,若集合对象key有重,可根据(k1,k2)->k1设置<保留k1,舍弃k2>.)
7、求和
基本类型:int sumAge = userList.stream().mapToInt(User::getAge).sum();
其他:BigDecimal totalMemberNum = userList.stream().map(User::getMemberNum).reduce(BigDecimal.ZERO, BigDecimal::add);
(其中,若bigDecimal对象为null,可filter()过滤掉空指针.)
8、最值
Date minDate = userList.stream().map(User::getCreateTime).min(Date::compareTo).get();
Date maxDate = userList.stream().map(User::getCreateTime).max(Date::compareTo).get();
User maxUp = userList.stream().max(Comparator.comparingInt(User::getAge)).get();
以上是关于JDK 1.8 Lambda表达式集合分组条件过滤组装去重排序转换求和最值的主要内容,如果未能解决你的问题,请参考以下文章