3

I am trying to throw an unechecked runtime exception in a nested stream. For some reason, this seems not possible. Why?

See example below. Please note that the logic does not make much sense. It 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());
}

1 Answers1

3

It seems the compiler can't 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());
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    Thanks. I'll try to report to javac buglist. –  Jul 15 '15 at 07:36
  • 3
    @DaveTeezo I don't think it's a bug - type inference does not work well with method chaining, but that is due to the specification rather than the implementation. See for example: http://stackoverflow.com/questions/24794924/generic-type-inference-not-working-with-method-chaining – assylias Jul 15 '15 at 09:51