stream 过滤俩个字段_Java8 使用 stream().filter()过滤符合条件List对象进行添加

常见的用法如下:

//查找身高在1.8米及以上的男生

List boys = studentList.stream().filter(s->s.getGender() && s.getHeight() >= 1.8).collect(Collectors.toList());

没用之前的写法是这样:

@Override

public List queryApiGroupList() {

List resGrpList =new ArrayList<>();

List grpList = apiGroupDao.queryAllGroup();

if (grpList != null && grpList.size() > 0) {

for (ApiGroupDTO apigrp : grpList) {

ApiGroupEntityDTO resApiGroup = new ApiGroupEntityDTO();

resApiGroup.setGroupId(apigrp.getGroupId());

resApiGroup.setGroupName(apigrp.getGroupName());

resApiGroup.setSort(apigrp.getSort());

resApiGroup.setApiCount(apigrp.getApiCount());

resGrpList.add(resApiGroup);

}

}

List apiIngrpList = apiGroupDao.queryAllApiInGroup();

if(apiIngrpList!=null&&apiIngrpList.size()>0){

for(ApiGroupEntityDTO resGrp:resGrpList){

List resApiList = new ArrayList<>();

for(ApiGroupDTO apiInGrp:apiIngrpList){

if(resGrp.getGroupId().equals(apiInGrp.getGroupId())){

ApiInformationDTO resApi= new ApiInformationDTO();

resApi.setApiId(apiInGrp.getApiId());

resApi.setApiName(apiInGrp.getApiName());

resApiList.add(resApi);

}

}

if(resApiList!=null&&resApiList.size()>0){

resGrp.setApiList(resApiList);

}

}

}

return resGrpList;

}

用了之后的写法是这样:

@Override

public List queryApiGroupList() {

List grpList = apiGroupDao.queryAllGroup();

List apiIngrpList = apiGroupDao.queryAllApiInGroup();

List resGrpList = grpList.stream().map(apiGroupDTO -> {

ApiGroupEntityDTO resApiGroup = new ApiGroupEntityDTO();

BeanUtils.copyProperties(apiGroupDTO,resApiGroup);

return resApiGroup;

}).collect(Collectors.toList());

resGrpList.forEach(apiGroupEntityDTO -> {

List apiInfoList = apiIngrpList.stream().filter(apiGroupDTO -> apiGroupDTO.getGroupId().equals(apiGroupEntityDTO.getGroupId())).map(apiGroup -> {

ApiInformationDTO resApi = new ApiInformationDTO();

BeanUtils.copyProperties(apiGroup, resApi);

return resApi;

}).collect(Collectors.toList());

apiGroupEntityDTO.setApiList(apiInfoList);

});

return resGrpList;

}

其中的实体类为:

@Data

public class ApiGroupEntityDTO implements Comparable,Serializable {

/**

* 组id

*/

private Long groupId;

/**

* 组名称

*/

private String groupName;

/**

* 排序字段

*/

private int sort;

/**

* 每个分组中的api数量

*/

private int apiCount;

/**

* 分组下的api集合

*/

private List apiList;

@Override

public int compareTo(ApiGroupEntityDTO o) {

int i = this.getSort() - o.getSort();//按照排序字段进行排序

return i;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值