How to transform a Java stream into a sliding window?

前端 未结 6 1587
天涯浪人
天涯浪人 2020-12-28 17:49

What is the recommended way to transform a stream into a sliding window?

For instance, in Ruby you could use each_cons:

irb(main):020:0> [1,2,3,4]         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 18:35

    if you want to bring the whole power of Scala's persistent collections to Java, you may use the library Javaslang.

    // this imports List, Stream, Iterator, ...
    import javaslang.collection.*;
    
    Iterator.range(1, 5).sliding(3)
            .forEach(System.out::println);
    // --->
    // List(1, 2, 3)
    // List(2, 3, 4)
    
    Iterator.range(1, 5).sliding(2, 3)
            .forEach(System.out::println);
    // --->
    // List(1, 2)
    // List(4)
    
    Iterator.ofAll(javaStream).sliding(3);
    

    You may not only use Iterator, this also works for almost any other Javaslang collection: Array, Vector, List, Stream, Queue, HashSet, LinkedHashSet, TreeSet, ...

    (Overview Javaslang 2.1.0-alpha)

    Disclaimer: I'm the creator of Javaslang

提交回复
热议问题