如何使用Future修复Java Lambda过滤器(缺少返回语句)

时间:2018-12-20 08:12:39

标签: java lambda

    How to solve java lambda filter future collection?

    I got a future collection, And I want to filter out the false result returned in the collection, but using lambda to report (Missing return statement),I want to get a collection looks like List<Map<String, Object>>, What should I do to achieve filtering? Thanks ^_^

        List<Future<Map<String, Object>>> future = 
            lists
                    .stream()
                    .map(i -> service.submit(new some(i)))
                    .collect(Collectors.toList());

                    future.stream().filter(i -> {
                        try {
                            i.get().get("success").equals(Boolean.FALSE);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }).findAny().get().get();

    [![enter image description here][1]][1]



    The `Map<String, Object>` structure looks like this  `{"success":"false","msg":"I got error"}`


      [1]: https://i.stack.imgur.com/mIWfy.png

任何人都可以帮助转换为lambda表达式吗? 上面的lambda表达式是对以下for循环的重写,我只想得到错误的结果, 我写的lambda表达式不正确,请帮忙写一个正确的表达式,谢谢

                List<Future<Map<String, Object>>> tfFuture = lists.stream().map(i -> service.submit(new what(i))).collect(Collectors.toList());
        enter code here

    for(int i=0;i<tfFuture.size();i++){
                    if(tfFuture.get(i).get().get("success").equals(Boolean.TRUE)){
                        break;
                    }
                    return tfFuture.get(i).get();
                }

2 个答案:

答案 0 :(得分:4)

所有执行路径中都必须具有return语句:

future.stream().filter(i -> {
    try {
        return i.get().get("success").equals(Boolean.FALSE);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    return false; // depending on what you wish to return in case of exception
}).findAny().get().get();

答案 1 :(得分:0)

您可以一次性完成此操作,并根据需要创建列表。

包括返回值以消除IDE警告。

List<Future<Map<String, Object>>> future =
        childIds.getChildOrder()
                .stream()
                .map(i -> service.submit(new Some(i)))
                .filter(i -> {
                    try {
                        return Boolean.FALSE.equals(i.get().get("success"));
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace(); //try to use a logger instead
                    }
                    return false;
                })
                .collect(Collectors.toList());

我真的会看一下您要在这里做什么。可能有一种更简单的方法。