Java8中stream的应用

排序

/**
     * 按照code排序 以|分割  举例: 0|1|2|3
     */
    private String getJoiningStr(List<CAutoDistributionInfo> list) {
        return list.stream().sorted(Comparator.comparing(CAutoDistributionInfo::getCode)).map(e -> String.valueOf(e.getCode())).collect(Collectors.joining("|")) + "|";
    }

 

复制代码
// 按照指定条件排序
public List<UserStationEntity> selectUserStation() {
Map<String, Integer> sortMap = new HashMap<>();
sortMap.put("cc.dcc", 1);
sortMap.put("cc.coperation", 2);

List<UserStationEntity> list = userStationMapper.selectList(null);
return list.stream().sorted(
Comparator.comparing(UserStationEntity::getStationCode, (x, y) -> {
return sortMap.get(x).intValue() - sortMap.get(y);
}).thenComparing(UserStationEntity::getCreateUsername)
).collect(Collectors.toList());
}


// 报价状态(1:待接受,2:已接受,3:回绝,4:已拒绝,5:已取消,6:无效)
List<Integer> orderStatus = offerCarPage.stream().sorted(
Comparator.comparing(OfferCarResourceModel::getExtendModel, Comparator.comparingInt(x -> Optional.ofNullable(x.getOrderStatus()).orElse(0))))
.map(item -> Integer.parseInt(item.getOfferStatus()))
.collect(Collectors.toList());
复制代码

 


List转换为Map

1.key和value都是对象中的某个属性值。

Map<String, String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId, User::getName));

 

 2.key是对象中的某个属性值,value是对象本身(使用返回本身的lambda表达式)。
Map<String, User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId, User -> User));

 

3.key是对象中的某个属性值,value是对象本身(使用Function.identity()的简洁写法)。

Map<String, User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
 

4.key是对象中的某个属性值,value是对象本身,当key冲突时选择第二个key值覆盖第一个key值。

如果不正确指定Collectors.toMap方法的第三个参数(key冲突处理函数),那么在key重复的情况下该方法会报出【Duplicate Key】的错误导致Stream流异常终止,使用时要格外注意这一点。

Map<String, User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (oldValue, newValue) -> newValue));

用groupingBy 或者 partitioningBy进行分组
根据一个字段或者属性分组也可以直接用groupingBy方法,很方便。

复制代码
public class Student{
    //年级
    private String grade;
    //班级
    private String classNumber;
    //姓名
    private String name;
    //年龄
    private int age;
    //地址
    private String address;
    //数学成绩
    private int mathScores;
    //语文成绩
    private int chainessScores;
}
复制代码
Map<String, List<Student>> collect = students.stream().collect(Collectors.groupingBy(Student::getClassNumber));
System.out.println(JSON.toJSONString(collect));

 

List转化成树形

复制代码
private DetectResultResModel buildDetectResultResModel(DetectResultRes res) {
        DetectResultResModel resModel = new DetectResultResModel();
        BeanUtils.copyProperties(res, resModel);
        // 查询files
        String fileIds = res.getFileIds();
        if (StringUtils.isNotBlank(fileIds)) {
            List<String> fileIdsList = Arrays.asList(fileIds.split(","));
            resModel.setFiles(fileFeignService.queryFileVisitUrl(fileIdsList, null, 900L, "1"));
        }
        return resModel;
    }

/**
* 根据检测大类查询检测项/检测结果
*
* @param req
*/
@PostMapping("/selectDetectResultRes")
public ResultModel selectDetectResultRes(@RequestBody DetectResultReq req) {
PageListModel<DetectResultRes> pageListModel = detectClient.selectDetectResultRes(req);
List<DetectResultRes> list = pageListModel.getList();

List<DetectResultResModel> resultList = list.stream().map(item -> this.buildDetectResultResModel(item)).collect(Collectors.toList());
Map<Integer, List<DetectResultResModel>> perListMap = resultList.stream().collect(Collectors.groupingBy(DetectResultResModel::getParentId));
resultList.stream().forEach(item -> item.setChildren(perListMap.get(item.getDetectBaseId())));

return ResponseDataUtil.success(resultList.get(0));
}
 
复制代码

 

2个集合中的差集

List<GoodModel> goodModelList=getGoodModelList();
List<GoodVo> goodVoList=getGoodVoList();
//比较两个集合,去除goodVoList中包含goodModelList的商品
List<GoodVo> goodVos=goodVoList.stream().filter(p ->
                !goodModelList.stream()
                        .map(b ->b.getNumber()).collect(Collectors.toList())
                        .contains(p.getNumber())).collect(Collectors.toList());

 

提取属性

复制代码
提取单个属性:获取所有的用户名,并去重
userList.stream()
.map(User::getName)
.distinct()
.collect(Collectors.toList());

 

提取多个属性:将menuId和menuName组成map(menuId唯一)

userList.stream()
.collect(Collectors.toMap(User::getMenuId, User::getMenuName)));

 

提取多个属性:将menuId和menuName组成map(menuId不唯一)

userList
//去重
.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(User :: getMenuId))), ArrayList::new))
//转map
.stream().collect(Collectors.toMap(User::getMenuId, User::getMenuName)));

复制代码

 

 

 Optional<UserReq> lastUserReq = toAssignUserList.stream().filter(p -> p.getUserId().equals(lastClueAssignLogEntity.getAdId())).findFirst();
            if (lastUserReq.isPresent()) {
                toIndex = toAssignUserList.lastIndexOf(lastUserReq.get()) + 1;
            }

 

移除元素

showList.forEach(f -> list.removeIf(item -> item.getId().equals(f.getColumnId())));
posted @   亲爱的阿道君  阅读(165)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示