The most idiomatic way to create a cyclic and infinite range of integers in Java 8

In ruby ​​you can do something like this

a = ["a", "b", "c"]
a.cycle {|x| puts x }  # print, a, b, c, a, b, c,.. forever.
a.cycle(2) {|x| puts x }  # print, a, b, c, a, b, c.

and it's just beautiful.

The closest equivalent in Java 8 would be:

Stream<Integer> iterator = Stream.iterate(new int[] {0, 0}, p -> new int[]{p[0] + 1, (p[0] + 1) % 2}).map(el -> el[1]);
Iterator<Integer> iter = iterator.iterator();
System.out.println(iter.next());//0
System.out.println(iter.next());//1
System.out.println(iter.next());//0
System.out.println(iter.next());//1

Is there a better way and more idiomatic to do this in Java?

Update

I just want to state here that the closest solution to my problem was

IntStream.generate(() -> max).flatMap(i -> IntStream.range(0, i)) 

Thanks @Hogler

+4
source share
2 answers

you can use

String[] array = { "a", "b", "c" };
Stream.generate(() -> array).flatMap(Arrays::stream).forEach(System.out::println);

for printing a b cforever and

String[] array = { "a", "b", "c" };
Stream.generate(() -> array).limit(2).flatMap(Arrays::stream).forEach(System.out::println);

print a b ctwice.

It does not even require an existing array:

Stream.generate(() -> null)
      .flatMap(x -> Stream.of("a", "b", "c"))
      .forEach(System.out::println);

respectively.

Stream.generate(() -> null).limit(2)
      .flatMap(x -> Stream.of("a", "b", "c"))
      .forEach(System.out::println);

you can also use

IntStream.range(0, 2).boxed()
      .flatMap(x -> Stream.of("a", "b", "c"))
      .forEach(System.out::println);
+5
source

, , . - :

String[] array = { "a", "b", "c" };

Stream.iterate(0, i -> (i + 1) % array.length)
        .map(i -> array[i])
        .forEach(System.out::println); // prints a, b, c forever

Stream.iterate(0, i -> (i + 1) % array.length)
        .map(i -> array[i])
        .limit(2 * array.length)
        .forEach(System.out::println); // prints a, b, c 2 times

nCopies, array.length:

Collections.nCopies(2, array).stream()
        .flatMap(Arrays::stream)
        .forEach(System.out::println); // prints a, b, c 2 times

, , ruby, java ( )

+3

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


All Articles