I'm having a hard time understanding how to handle exceptions when using a Java 8 stream. I would like to add objects to an empty list, and each object gets returned from a function that can potentially throw an exception depending on what the input is. If an exception is thrown for only certain values on the input list, I want it to continue to loop through the remainder of the input list. It seems easy to do with a for loop:
List<Item> itemList = new ArrayList<>();
List<Input> inputs = getInputs(); //returns a list of inputs
int exceptionCount = 0;
// If an exception is thrown
for (Input input : inputs){
try {
itemList.add(getItem(input));
} catch (Exception e ) {
// handle exception from getItem(input)
exceptionCount = exceptionCount + 1;
}
}
It seems like it may be possible to achieve this with a Java stream, but I'm not quite sure how to handle the exception that could be thrown by the getItem()
function.
Here's what I have so far:
final List<Item> itemList = new ArrayList<>();
try {
itemList = getInputs().stream()
.map(this::getItem)
.collect(Collectors.toList());
} catch (Exception e ) {
// handle exception from getItem(input)
exceptionCount = exceptionCount + 1;
}
The above obviously won't work because as soon as there is one exception thrown from getItem
, the loop will not continue and only one exception will be thrown for the entire stream. Is there any way I can achieve the same implementation as my basic for loop with Java 8 streams?