Skip to content

Instantly share code, notes, and snippets.

@softprops
Created June 16, 2021 18:50
Show Gist options
  • Save softprops/310b44baf773d157cbbaf0de02a721b5 to your computer and use it in GitHub Desktop.
Save softprops/310b44baf773d157cbbaf0de02a721b5 to your computer and use it in GitHub Desktop.
NonRepeatingStream.java
import java.util.stream.*;
import java.util.concurrent.*;
import java.util.*;
public <T> Stream<T> nonRepeatingStream(List<T> src) {
IntSupplier index = () -> ThreadLocalRandom.current().nextInt(0, src.size());
return Stream.iterate(
index.getAsInt(),
(prev) -> {
int next = index.getAsInt();
while (prev == next) {
next = index.getAsInt();
}
return next;
}
).map(src::get);
}
Stream<String> stream = nonRepeatingStream(Arrays.asList("a", "b"));
stream.limit(10).forEach(el -> System.out.println(el));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment