Java Stream: Convert User Input to Packages

I would like to stream ints (from user input) and output a stream of lists of a certain length - effectively dose user input to batches, and then do some other work on it. Basically, for user input: 1,2,3,4,5,6,7,8,9I could divide it into these parties. <1,2,3> , <4,5,6> , <7,8,9>As soon as I collect 3 numbers, I want to create a list for the next processing step, which I need to work on. I am trying to do this using lamda and stream operations in java 8 to learn more about this.

the only related sample I could find is http://www.nurkiewicz.com/2014/07/grouping-sampling-and-batching-custom.html with a custom collector that does something very similar to what what I want - the problem of using the collector is that I do not want to wait for the end of the stream, but I process each batch when it is ready.

Is there an easy way to do this? Somehow not suitable for using Java 8 threads for this kind of operation?

+4
source share
1 answer

, API Java-8. -, , , , ( ). Stream API , . , (, protonpack StreamUtils.windowed), , .

, Java-8 (, , ) ( BufferedReader.lines()). Java-9 , Scanner (. JDK-8072722), .

, , , . takeWhile, Java-9 (. JDK-8071597).

, StreamEx, :

Scanner sc = new Scanner(System.in).useDelimiter("[\n\r,\\s]+");
Iterable<String> iterable = () -> sc;
// Supplier which returns Lists of up to 3 numbers from System.in
Supplier<List<Integer>> triples = () -> StreamEx.of(iterable.spliterator())
        .map(Integer::valueOf).limit(3).toList();
StreamEx.generate(triples).takeWhile(list -> !list.isEmpty())
        // replace with your own stream operations
        // they will be executed as soon as three numbers are entered
        .forEach(System.out::println);

StreamEx, , StreamEx.takeWhile, backport Java-9 Stream.takeWhile.

jOOL, :

Scanner sc = new Scanner(System.in).useDelimiter("[\n\r,\\s]+");
Supplier<List<Integer>> triples = () -> Seq.seq(sc).map(Integer::valueOf).limit(3).toList();
Seq.generate(triples).limitUntil(List::isEmpty)
    .forEach(System.out::println);

. Spliterator , jOOL Seq.seq(Iterator).

, . , , - :

import static com.codepoetics.protonpack.StreamUtils.*;

Scanner sc = new Scanner(System.in).useDelimiter("[\n\r,\\s]+");
Stream<List<Integer>> stream = takeUntil(windowed(
    stream(() -> sc).map(Integer::valueOf), 3, 3), List::isEmpty);
stream.forEach(System.out::println);

, - , . , 3 . ​​ trunc, .

+5

Source: https://habr.com/ru/post/1617511/


All Articles