Is it possible to use Streams.intRange function?

后端 未结 3 1587
挽巷
挽巷 2021-01-16 07:07

I wanted to use Streams.intRange(int start, int end, int step) to achieve reverse ordered stream. However it seems that java.util.Streams class is no longer available (howev

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-16 07:38

    You can create it based on an infinite stream:

    public static IntStream intRange(int start, int end, int step ) {
        if ( step == 0 ) {
            throw new IllegalArgumentException("Cannot iterate with a step of zero");
        }
        final int limit = (end - start + step) / step;
        if ( limit < 0 ) {
            return IntStream.empty();
        }
        return IntStream.iterate(start, x -> x + step )
                        .limit( limit );
    }
    

    If the range doesn't make sense (e.g. range from 7 to 2 in steps of 1) you get an empty stream.

    The limit is inclusive. That is, range from 2 to 8 in steps of 2 will give you 2,4,6,8. If you want it to be exclusive (without the 8), change the limit to:

    final int limit = (end - start) / step;
    

    Possible usage:

    intRange(8 ,2, -2).forEach(System.out::println);
    

    Output:

    8
    6
    4
    2
    

提交回复
热议问题