Assertions in Streams

iberbeu :

I know I can filter a stream to get only those elements that are not null, and then do with them whatever I need. Something like this:

myList.stream().filter(element -> element != null).doOtherThings...

Is there a way to assert that the elements are not null in a stream function, so that it goes through all elements and if it finds one being null, it throws an exception? I've been thinking of something like the following:

myList.stream().assert(Objects::nonNull).doOtherThings...
Ole V.V. :

There are some very good suggestions already. Allow me to supplement. If what you are after is an assertion as in an assert statement, I would like to make this explicit in the code in order to guide the reader about my purpose. To assert that your original list doesn’t contain any nulls:

    assert ! myList.contains(null);

If the assertion is to be checked somewhere down the stream pipeline, the simple way is:

    assert myList.stream().map(this::transform).allMatch(Objects::nonNull);

If you don’t want to create a separate stream for the assertion but prefer to assert in the middle of your existing stream pipeline, use for example:

        myList.stream()
                .peek(e -> { assert e != null; })
                .toArray();

You may worry that the use of peek is not so nice, which is also why I mention this option last. peek is documented to exist “mainly to support debugging” (quote taken out of its context), so you may say that it’s related to the purpose of assert and thus defend its use in this case.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84818&siteId=1