How do you create an endless repeating thread from a final thread in Java 8?

How can I turn a finite stream of things Stream<Thing>into an endless repeating stream of things?

+1
source share
3 answers

If you have a finite stream and know that it fits into memory, you can use an intermediate collection.

final Stream<Thing> finiteStream = ???;
final List<Thing> finiteCollection = finiteStream.collect(Collectors.toList());
final Stream<Thing> infiniteThings = Stream.generate(finiteCollection::stream).flatMap(Functions.identity());
0
source

Boris Spider is right: you can skip a stream only once, so you need Supplier<Stream<Thing>>or need a collection.

<T> Stream<T> repeat(Supplier<Stream<T>> stream) {
    return Stream.generate(stream).flatMap(s -> s);
}

<T> Stream<T> repeat(Collection<T> collection) {
    return Stream.generate(() -> collection.stream()).flatMap(s -> s);
}

Call examples:

Supplier<Stream<Thing>> stream = () ->
    Stream.of(new Thing(1), new Thing(2), new Thing(3));

Stream<Thing> infinite = repeat(stream);
infinite.limit(50).forEachOrdered(System.out::println);

System.out.println();

Collection<Thing> things =
    Arrays.asList(new Thing(1), new Thing(2), new Thing(3));

Stream<Thing> infinite2 = repeat(things);
infinite2.limit(50).forEachOrdered(System.out::println);
+4
source

Guava , .

final Collection<Thing> thingCollection = ???;
final Iterable<Thing> cycle = Iterables.cycle(thingCollection);
final Stream<Thing> things = Streams.stream(cycle);

, Stream, .

+1

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


All Articles