How to fix java lambda filter(missing return statement) with future

后端 未结 2 1411
北恋
北恋 2021-01-14 01:02

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

相关标签:
2条回答
  • 2021-01-14 01:51

    You must have return statements in all execution paths:

    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();
    
    0 讨论(0)
  • 2021-01-14 01:58

    You can do this in one go and create the list with what you need.

    Include the return value to eliminate the IDE warning.

    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());
    

    I'd really take a look at what you're trying to do here though. There's likely a simpler way.

    0 讨论(0)
提交回复
热议问题