How to implement a Java stream?

后端 未结 5 904
悲哀的现实
悲哀的现实 2020-12-01 06:34

I want to implement a Stream.

I don\'t want to just use implements Stream, because I would have to implement a ton of met

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 06:53

    You usually do not need to write your own stream class. Instead you can create stream by existing methods. For instance, here is how to create a stream of the value 1, 100:

      AtomicInteger n = new AtomicInteger(0);
      Stream stream = Stream.generate(() -> n.incrementAndGet()).limit(100);
    

    so in here we created an infinite stream of integers: 1, 2, 3, .... then we used limit(100) on that infinite stream to get back a stream of 100 elements.

    For clarity, if you want a stream of integers (at fixed intervals) you should use IntStream.range(). This is just an example to show how streams can be defined using Stream.generate() which gives you more flexibility as it allows you to use arbitrary logic for determining steam's elements.

提交回复
热议问题