小编ben*_*nez的帖子

如何在Java 8 Stream.flatMap(..)中捕获异常

给定一个Stream和一个方法返回一个Stream不同的参数作为数据源,我正在寻找一种方法来合并流,flatMap(..)Exceptions在执行过程中捕获某些.

我们来看下面的代码片段:

public class FlatMap {

    public static void main(final String[] args) {
        long count;

        // this might throw an exception
        count = Stream.of(0.2, 0.5, 0.99).flatMap(chance -> getGenerator(chance, 20)).count();

        // trying to catch the exception in flatMap() will not work
        count = Stream.of(0.2, 0.5, 0.99).flatMap(chance -> {
            try {
                return getGenerator(chance, 20);
            } catch (final NullPointerException e) {
                return Stream.empty();
            }
        }).count();

        System.out.println(count);
    }

    // !! we cannot change this method, we …
Run Code Online (Sandbox Code Playgroud)

java exception java-8 java-stream

6
推荐指数
1
解决办法
678
查看次数

Eclipse Neon无法编译;模棱两可的方法

我们想从Eclipse Mars升级到Neon,但是我们的项目无法编译。在Mars中,以下代码会编译:

public class AmbiguousMWE {

    private <T, C extends Collection<T>> void foo(final C c, final Function<T, T> b) {}

    private <T> void foo(final T t, final Function<T, T> f) {}

    private void test() {
        foo(new ArrayList<>(), this::get);
    }

    private Object get(final Object o) {
        return null;
    }

    private Object get() {
        return null;
    }

}
Run Code Online (Sandbox Code Playgroud)

但是,如果我们删除最后一个get()方法,则由于错误'代码foo(ArrayList,Function)对于AmbiguousMWE类型是不明确的,因此代码无法编译。您可以尝试更改方法的顺序,并且可能会遇到不同的编译器行为。

最重要的是,在升级到Eclipse Neon时,总是会发生此错误,并且有很多源代码无法再编译。

因此,首先,我不知道第二个get()方法与该错误有什么关系,第二,可以做什么来告诉Eclipse仍然编译我们的代码?

感谢您的任何想法。

java eclipse ambiguous eclipse-mars eclipse-neon

5
推荐指数
0
解决办法
593
查看次数