Created
April 21, 2021 14:33
-
-
Save aaiezza/1161a9e99b21e0cc18e341a9c61dec05 to your computer and use it in GitHub Desktop.
Choose a random option
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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