Can you split a stream into two streams?

前端 未结 10 803
栀梦
栀梦 2020-11-27 12:03

I have a data set represented by a Java 8 stream:

Stream stream = ...;

I can see how to filter it to get a random subset - for exa

10条回答
  •  一向
    一向 (楼主)
    2020-11-27 12:24

    I stumbled across this question while looking for a way to filter certain elements out of a stream and log them as errors. So I did not really need to split the stream so much as attach a premature terminating action to a predicate with unobtrusive syntax. This is what I came up with:

    public class MyProcess {
        /* Return a Predicate that performs a bail-out action on non-matching items. */
        private static  Predicate withAltAction(Predicate pred, Consumer altAction) {
        return x -> {
            if (pred.test(x)) {
                return true;
            }
            altAction.accept(x);
            return false;
        };
    
        /* Example usage in non-trivial pipeline */
        public void processItems(Stream stream) {
            stream.filter(Objects::nonNull)
                  .peek(this::logItem)
                  .map(Item::getSubItems)
                  .filter(withAltAction(SubItem::isValid,
                                        i -> logError(i, "Invalid")))
                  .peek(this::logSubItem)
                  .filter(withAltAction(i -> i.size() > 10,
                                        i -> logError(i, "Too large")))
                  .map(SubItem::toDisplayItem)
                  .forEach(this::display);
        }
    }
    

提交回复
热议问题