Can you split a stream into two streams?

前端 未结 10 799
栀梦
栀梦 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:43

    I stumbled across this question to my self and I feel that a forked stream has some use cases that could prove valid. I wrote the code below as a consumer so that it does not do anything but you could apply it to functions and anything else you might come across.

    class PredicateSplitterConsumer implements Consumer
    {
      private Predicate predicate;
      private Consumer  positiveConsumer;
      private Consumer  negativeConsumer;
    
      public PredicateSplitterConsumer(Predicate predicate, Consumer positive, Consumer negative)
      {
        this.predicate = predicate;
        this.positiveConsumer = positive;
        this.negativeConsumer = negative;
      }
    
      @Override
      public void accept(T t)
      {
        if (predicate.test(t))
        {
          positiveConsumer.accept(t);
        }
        else
        {
          negativeConsumer.accept(t);
        }
      }
    }
    

    Now your code implementation could be something like this:

    personsArray.forEach(
            new PredicateSplitterConsumer<>(
                person -> person.getDateOfBirth().isPresent(),
                person -> System.out.println(person.getName()),
                person -> System.out.println(person.getName() + " does not have Date of birth")));
    

提交回复
热议问题