How to match stream elements but return false if non exists?

后端 未结 6 1732
无人共我
无人共我 2020-12-09 11:58

I have a stream and would like to check if all match a filter. If all match, return true.

But, if the stream is empty, I\'d like to return false

6条回答
  •  一生所求
    2020-12-09 12:53

    The following code will work (I tested it).

    public static boolean validate(Stream stream) {
        return stream.reduce((whatever1, whatever2) -> Whatever.someCheck(whatever1) ? whatever2 : whatever1)
                .map(Whatever::someCheck).orElse(false);
    }
    

    How it works? We use reduce operation to check that every element matches the predicate, if it fails, we keep returning the failing one (in ternary operation). At the end, we map the reduced Whatever object to boolean, and if it's true: then all matched and this is not empty (orElse(false)).

提交回复
热议问题