A relatively elegant solution would be to use anymatch to check if there is any scenario where you should launch Exception and in a second moment, if there was no Exception, you would follow with your processing normally, not needing capture after after it has been validated that your data are consistent.
Set<Integer> result = (Set<Integer>) Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
if(result.stream().anyMatch(n -> n % 2 != 0)){
throw new Exception();
}
{seu código}
Considering the fact that the lambda does not run exactly at the place where it was written, but somewhere "magical" and unrelated from your jdk that location would be where your Exception would be checked, not interrupting execution. To solve this we must create a wrapper that aims to translate a checked Exception to a not checked and "pop" the failure.
public class Main {
public static void main(String[] args) {
Set result = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9).stream()
.filter(n ->uncheckCall(() -> {
if(n % 2 == 0){
return true;
}else{
throw new Exception();
}
}))
.map(String::valueOf)
.collect(Collectors.toSet());
System.out.println(result);
}
public static <T> T uncheckCall(Callable<T> callable) {
try {
return callable.call();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Personally I prefer the first solution, but there is a second possibility.
But the
filter
have you only taken even numbers, so why check again if all are even? Or you want to throw an exception if you have no pair?– hkotsubo
It is a hypothetical example, the validation could be if all pairs are less than or equal to 10, the objective and make a validation whatever.
– Henrique Luiz
Maybe use
allMatch
solve. The problem is that this is a terminal operation and cannot be usedcollect
after. It may be simpler to include all thefilter
and at the end check whether theSet
is empty, for example.– hkotsubo