我有一段代码看起来像这样。
我读过两条关于此的相互矛盾的(?)“规则”。
- 那个
.map
不应该有副作用 .foreach
不应该 更新一个可变变量(所以如果我重构使用 foreach 和 填充结果列表,然后打破它)如 http://files.zeroturnaround.com/pdf/zt_java8_streams_cheat_sheet.pdf 中所述
我该如何解决它以便我使用流并仍然返回一个列表,或者我应该跳过流?
@Transactional
public Collection<Thing> save(Collection<Thing> things) {
return things.stream().map(this::save).collect(Collectors.toList());
}
@Transactional
public Thing save(Thing thing) {
// org.springframework.data.repository.CrudRepository.save
// Saves a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely.
Thing saved = thingRepo.save(thing);
return saved;
}
最佳答案
那篇论文不是说共享可变状态吗?在您的情况下,如果您在方法内声明列表然后使用 forEach
,一切都很好。第二个回答here确切地提到你正在尝试做什么。
关于带有副作用的 Java 流映射和收集或 foreach 并填充结果列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42951942/