Search code examples
javaforeachjava-8java-streammap-function

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


I have a piece of code that looks something like this.

I have read two contradicting(?) "rules" regarding this.

How can I solve it so I use streams and still returns a list, or should I simply skip streams?

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

Solution

  • Doesn't that paper say shared mutable state? In your case if you declare the list inside the method and then use forEach, everything is fine. The second answer here mentions exactly what you are trying to do.