The logic here is basically "the result of the last successful operation".
Assuming you don't need the failedCount
(you don't show it being used), you can do that like this: map successful operations to a present Optional
, failed operations to an absent Optional
; and just take the last present optional:
Optional<List<List2Class>> opt = list1.stream()
.flatMap(element -> Stream.of(runOperation(someclass::method1, element), runOperation(someclass::method2, element))
.reduce((a, b) -> !b.isPresent() ? a : b);
where runOperation
is something like:
Optional<List<List2Class>> runOperation(Function<String, List<List2Class>> operation, String parameter) {
try {
return Optional.of(operation.apply(parameter));
} catch (Exception e) {
return Optional.absent();
}
}
You then need to decide what value list2
should have if no operations succeed.
If you actually do need the failedCount
, you can break this up a bit:
Stream<Optional<List<List2Class>>> intermediate =
list1.stream()
.flatMap(element -> Stream.of(runOperation(someclass::method1, element), runOperation(someclass::method2, element));
Map<Boolean, List<Optional<List<List2Class>>>> partitioned =
intermediate.collect(Collectors.partitioningBy(Optional::isPresent));
Now partitioned.get(true)
has all the successful results, while partitioned.get(false)
has all the failed results. So:
Optional<List<List2Class>> opt = partitioned.get(true).stream().reduce((a, b) -> !b.isPresent() ? a : b);
long failedCount = partitioned.get(false).size();