Java 带有副作用的流映射和收集或 foreach 并填充结果列表

Java streams map with sideeffect and collect or foreach and populate a result-list

我有一段代码看起来像这样。

关于这个,我读过两个相互矛盾的(?)"rules"。

我怎样才能解决这个问题以便我使用流并且仍然 returns 一个列表,或者我应该跳过流?

@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;
}

如果你根本不改变它,几乎没有理由去收集一个全新的 List。除此之外,您的用例基本上是遍历集合中的每个元素并保存可以通过使用 for-each.

简单实现的元素

如果由于某种原因 thingRepo.save(thing) 改变对象,你仍然可以 return 相同的集合,但此时它是一个隐藏的突变,自 thingRepo.save(thing) 以来根本不可见不建议。

那篇论文不是说 shared 可变状态吗?在你的情况下,如果你在方法中声明列表然后使用 forEach,一切都很好。第二个答案 here 准确地提到了你想要做什么。