Can you split a stream into two streams?

前端 未结 10 804
栀梦
栀梦 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条回答
  •  Happy的楠姐
    2020-11-27 12:34

    This was the least bad answer I could come up with.

    import org.apache.commons.lang3.tuple.ImmutablePair;
    import org.apache.commons.lang3.tuple.Pair;
    
    public class Test {
    
        public static  Pair splitStream(Stream inputStream, Predicate predicate,
                Function, L> trueStreamProcessor, Function, R> falseStreamProcessor) {
    
            Map> partitioned = inputStream.collect(Collectors.partitioningBy(predicate));
            L trueResult = trueStreamProcessor.apply(partitioned.get(Boolean.TRUE).stream());
            R falseResult = falseStreamProcessor.apply(partitioned.get(Boolean.FALSE).stream());
    
            return new ImmutablePair(trueResult, falseResult);
        }
    
        public static void main(String[] args) {
    
            Stream stream = Stream.iterate(0, n -> n + 1).limit(10);
    
            Pair, String> results = splitStream(stream,
                    n -> n > 5,
                    s -> s.filter(n -> n % 2 == 0).collect(Collectors.toList()),
                    s -> s.map(n -> n.toString()).collect(Collectors.joining("|")));
    
            System.out.println(results);
        }
    
    }
    

    This takes a stream of integers and splits them at 5. For those greater than 5 it filters only even numbers and puts them in a list. For the rest it joins them with |.

    outputs:

     ([6, 8],0|1|2|3|4|5)
    

    Its not ideal as it collects everything into intermediary collections breaking the stream (and has too many arguments!)

提交回复
热议问题