JDK1.8Lambda表达式集合分组、条件过滤、组装、去重、排
序、转换、求和、最值
在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
lambda编程+ ", sessionId=" + sessionId + ", createTime=" + createTime
+ ", updateTime=" + updateTime + ", age=" + age + "]";
}
}
在创建上述对象的前提下(List<User> userList不为空):
1、通过指定字段分组upingBy().
Map<String, List<User>> groupByStatus = userList.stream().upingBy(User::getStatus));
for (Map.Entry<String, List<User>> entry : Set()) {
String status = Key();
List<User> userList = Value();
}
2、通过条件过滤filter().
List<User> userListByStatus = userList.stream().filter(t -> t.getStatus().equals("100")).List());
3、获取list某个字段组装新list.
List<Long> userIdList = userList.stream().map(t -> t.getUserId()).List());
4、去重distinct().
List<Long> userIdList = userList.stream().distinct().List());
5、单字段多字段排序sort().
userList.sort(Comparatorparing(User::getUserId));
userList.sort(Comparatorparing(User::getUserId).thenComparing(User::getStatus));
{
注:若选择排序字段为null值,正序可
userList.sort(Comparatorparing(User::getUserId,Comparator.nullsFirst(Comparator.naturalOrder())))
}
6、list转map.
Map<Long, User> userMap = userList.stream().Map(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(ComparatorparingInt(User::getAge)).get();
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论