两个List通过相同的属性值进行个别属性赋值
需求:List<UserVo> 用户对象 List<CustLoginLogVo> 用户登录对象,将CustLoginLogVo集合中按用户全局ID进行匹配把用户的最后登录时间set到对应的UserVo中
UserVo:
public class UserVo{
@ApiModelProperty(value = "用户全局ID")
private String custGlobalId;
@ApiModelProperty(value = "最后登录时间")
private Date lastLoginTime;
}
CustLoginLogVo:
public class CustLoginLogVo{
@ApiModelProperty(value = "用户全局ID")
private String custGlobalId;
@ApiModelProperty(value = "最后登录时间")
private Date lastLoginTime;
}
实现代码:
List<UserVo> userList = new ArrayList<>();//这里要非空
List<CustLoginLogVo> custLoginLogVos = new ArrayList<>();//这里要非空 业务代码不贴出来
if(ValidateHelper.isNotEmptyCollection(custLoginLogVos)) {
userList = userList
.stream()
.map(user -> custLoginLogVos.stream()
.filter(log -> user.getCustGlobalId().equals(log.getCustGlobalId()))
.findFirst()
.map(log -> {
user.setLastLoginTime(log.getLoginTime());
return user;
})
.orElse(user))
.collect(Collectors.toList());
}
补充一点 Variable used in lambda expression should be final or effectively
int[] i = {1};
int j = 0;
List<CustLoginLogVo> custLoginLogVos = custLoginLogQueryRepository.listLastLogin(param);
custLoginLogVos.forEach(c->{{
i[0] = 1; //arr绕过
//j = 1; Variable used in lambda expression should be final or effectively final
}
});
对集合抽取属性求和
//获取阅读数
Integer readTatol = msgBrowseVos
.stream()
.filter(msgBrowse -> msgBrowse.getMsgType().equals(MsgBrowseConstants.msgType.READ))
.mapToInt(MsgBrowseVo::getCount)
.max()
.orElse(0);
//获取分享数
Integer shareTatol = msgBrowseVos
.stream()
.filter(msgBrowse -> msgBrowse.getMsgType().equals(MsgBrowseConstants.msgType.SHARE))
.mapToInt(MsgBrowseVo::getCount)
.max()
.orElse(0);