Is there a correct way to open a resource for each element in collection, than use stream api, do some map(), filter(), peek() etc. using the resource and than close the resource?
I have something like this:
List<String> names = getAllNames();
names.stream().map(n -> getElementFromName(n))
.filter(e -> e.someCondition())
.peek(e -> e.doSomething())
.filter(e -> e.otherCondition())
.peek(e -> e.doSomethingElse())
.filter(e -> e.lastCondition())
.forEach(e -> e.doTheLastThing());
This should work fine, except I'm opening a resource (e.g. db connection) in the getElementFromName method. Then I'm working with that resource in the other instance methods like someCondition or doSomething. And I have no idea how to close it correctly.
I know, that I'm using only intermediate operations on the stream. Which means, that all methods are evaluated in the forEach operation and performance should be ok because the iteration is done only once.
But I can't figure out how to close the resources opened for each element in the getElementFromName method.
I can save the list of all elements created by getElementFromName and close the resources later. But I would be just wasting space, keeping all the resources alive. Also there would be second iteration through the list of elements. Which makes avoiding stream api preferable in this case. So is there a way to somehow auto close the resource when I'm done using the element?
Also I know, it can be easily done using foreach lopp, I was just curious if it can be done using stream api.