Package api.util
Class RandomSelector<T>
java.lang.Object
api.util.RandomSelector<T>
- Type Parameters:
T-
A tool to randomly select elements from collections.
Example usages:
Random random = ...
Map<String, Double> stringWeights = new Hash<>();
stringWeights.put("a", 4d);
stringWeights.put("b", 3d);
stringWeights.put("c", 12d);
stringWeights.put("d", 1d);
RandomSelector<String> selector = RandomSelector.weighted(stringWeights.keySet(), s -> stringWeights.get(s));
List<String> selection = new ArrayList<>();
for (int i = 0; i < 10; i++) {
selection.add(selector.next(random));
}
-
Method Summary
Modifier and TypeMethodDescriptionReturns the next element using random.Returns a stream of elements using random.static <T> RandomSelector<T>uniform(Collection<T> elements) Creates a new random selector based on a uniform distribution.static <T> RandomSelector<T>weighted(Collection<T> elements, ToDoubleFunction<? super T> weighter) Creates a random selector among elements where the elements have a weight defined by weighter.
-
Method Details
-
uniform
Creates a new random selector based on a uniform distribution.A copy of elements is kept, so any modification to elements will not be reflected in returned values.
- Type Parameters:
T-- Parameters:
elements-- Returns:
- Throws:
IllegalArgumentException- if elements is empty.
-
weighted
public static <T> RandomSelector<T> weighted(Collection<T> elements, ToDoubleFunction<? super T> weighter) throws IllegalArgumentException Creates a random selector among elements where the elements have a weight defined by weighter.A copy of elements is kept, so any modification to elements will not be reflected in returned values.
- Type Parameters:
T-- Parameters:
elements-weighter-- Returns:
- Throws:
IllegalArgumentException- if elements is empty or if weighter returns a negative value or 0.
-
next
Returns the next element using random.- Parameters:
random-- Returns:
-
stream
Returns a stream of elements using random. The stream must use a terminal operation to become closed and free the resources it's been using.Even though this instance is thread-safe and for performance reasons, it is recommended to use a different stream per thread given that Random has performance drawbacks in multi-threaded environments.
- Parameters:
random-- Returns:
-