Java 8 Stream API:如何单语句批量设置流列表多属性
问题描述
现有如下代码片段,希望通过Stream API用单个语句为CtStaticIPDetailsList列表中的每个对象同时设置isDeleted、modifiedDate和modifiedBy三个属性,如何实现?
List<CtStaticIPDetailsList> ctStaticIPDetailsList = new ArrayList<>(); ctStaticIPDetailsList.stream().forEach(l -> l.setIsDeleted(true)); ctStaticIPDetailsList.stream() .forEach(l -> l.setModifiedDate(new Date())); ctStaticIPDetailsList.stream() .forEach(l -> l.setModifiedBy(boqCreationDTO.getUserId()));
解决方案
你可以在同一个forEach的Lambda表达式中依次调用三个set方法,只需要创建一次Stream就能完成所有属性设置:
ctStaticIPDetailsList.stream().forEach(l -> { l.setIsDeleted(true); l.setModifiedDate(new Date()); l.setModifiedBy(boqCreationDTO.getUserId()); });
补充说明
- 如果列表元素数量较大,可考虑使用并行流(
parallelStream())提升效率,但注意:若new Date()放在Lambda内部,并行执行时会为每个对象创建独立的Date实例;如果希望所有对象使用同一时间戳,建议提前创建好Date对象:Date now = new Date(); ctStaticIPDetailsList.parallelStream().forEach(l -> { l.setIsDeleted(true); l.setModifiedDate(now); l.setModifiedBy(boqCreationDTO.getUserId()); }); - 其实不依赖Stream,直接调用列表自带的
forEach方法也能实现相同效果,代码更简洁:Date now = new Date(); ctStaticIPDetailsList.forEach(l -> { l.setIsDeleted(true); l.setModifiedDate(now); l.setModifiedBy(boqCreationDTO.getUserId()); });
内容的提问来源于stack exchange,提问作者Rachit07
相关产品推荐
相关产品推荐

