Class WeightedSupplier<T>

  • Type Parameters:
    T - the supplied type
    All Implemented Interfaces:
    Function<Random,​T>, Supplier<T>

    public class WeightedSupplier<T>
    extends Object
    implements Supplier<T>, Function<Random,​T>
    This class implements a Supplier that randomly delegates to one of several (sub-)suppliers. Each sub-supplier is assigned a weight, which determines the probability of it being chosen upon calls to get().

    The add(Object, int) and add(Supplier, int) methods return a reference to this, so calls can be chained.

    Usage example:

     
     Supplier<String> mySupplier = ...;
     String str = new WeightedSupplier<String>()
      .add("foo", 5)
      .add(mySupplier, 10)
      .get();
     
     
    With a one-third chance, the value "foo" will be assigned to str. Otherwise (i.e., with a two-thirds chance), the result of mySupplier.get() will be assigned to str. Note that in the former case, mySupplier.get() will not even be invoked.
    • Constructor Detail

      • WeightedSupplier

        public WeightedSupplier()
    • Method Detail

      • add

        public WeightedSupplier<T> add​(T obj,
                                       int weight)
        Adds an object to be supplied with a given weight.
        Parameters:
        obj - the object to be supplied
        weight - the weight
        Returns:
        this
      • add

        public WeightedSupplier<T> add​(Supplier<? extends T> supplier,
                                       int weight)
        Adds a sub-supplier with a given weight.
        Parameters:
        supplier - the sub-supplier
        weight - the weight
        Returns:
        this
      • get

        public T get()
        Specified by:
        get in interface Supplier<T>