Skip to content

Instantly share code, notes, and snippets.

@aaiezza
Created April 21, 2021 14:33
Show Gist options
  • Save aaiezza/1161a9e99b21e0cc18e341a9c61dec05 to your computer and use it in GitHub Desktop.
Save aaiezza/1161a9e99b21e0cc18e341a9c61dec05 to your computer and use it in GitHub Desktop.
Choose a random option
import static java.util.Collections.shuffle;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toList;
import java.util.Optional;
import java.util.stream.Collector;
import java.util.stream.Stream;
public class RandomOptionChooser {
public Optional<Option> randomlyChooseAnOption(@lombok.NonNull final String... options) {
return randomlyChooseAnOption(Stream.of(options).map(Option::new).toArray(Option[]::new));
}
public Optional<Option> randomlyChooseAnOption(@lombok.NonNull final Option... options) {
return Stream.of(options).map(Option::new).collect(toSetAndShuffle()).findFirst();
}
@lombok.Value
private static class Option {
private final String name;
@Override
public String toString() {
return name;
}
}
private static <T> Collector<T, ?, Stream<T>> toSetAndShuffle() {
return collectingAndThen(
toList(),
a -> {
shuffle(a);
return a.stream();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment