Java8 - nested streaming and unchecked exception
I am trying to throw a thrown exception at runtime in a nested thread. For some reason this seems impossible. Why?
See example below. Please note that the logic doesn't make a lot of sense. This is just for demonstration purposes.
public static void main(String[] a) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.stream()
.map(item -> list.stream()
.filter(item2 -> item.equals(item2))
.findFirst()
.orElseThrow(RuntimeException::new))
.collect(Collectors.toList());
}
+3
source to share
1 answer
It seems the compiler cannot infer the type of the exception.
Just use
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.stream()
.map(item -> list.stream()
.filter(item2 -> item.equals(item2))
.findFirst()
.<RuntimeException>orElseThrow(RuntimeException::new))
.collect(Collectors.toList());
+3
source to share