All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.rkumsher.enums.RandomEnumUtils Maven / Gradle / Ivy

There is a newer version: 1.3
Show newest version
package com.github.rkumsher.enums;

import java.util.Collection;
import java.util.EnumSet;

import com.github.rkumsher.collection.IterableUtils;

/** Utility library to retrieve random elements from enum instances. */
public final class RandomEnumUtils {

  private RandomEnumUtils() {}

  /**
   * Returns a random element from the given enum class.
   *
   * @param enumClass enum class to return random element from
   * @param  the type of the given enum class
   * @return random element from the given enum class
   * @throws IllegalArgumentException if the given enumClass has no values
   */
  public static > T random(Class enumClass) {
    EnumSet enums = EnumSet.allOf(enumClass);
    return IterableUtils.randomFrom(enums);
  }

  /**
   * Returns a random element from the given enum class that's not in the values to exclude.
   *
   * @param enumClass enum class to return random element from
   * @param excludes values to exclude
   * @param  the type of the given enum class
   * @return random element from the given enum class that's not in the values to exclude.
   * @throws IllegalArgumentException if the given enumClass has no values
   */
  @SafeVarargs
  public static > T random(Class enumClass, T... excludes) {
    EnumSet enums = EnumSet.allOf(enumClass);
    return IterableUtils.randomFrom(enums, excludes);
  }

  /**
   * Returns a random element from the given enum class that's not in the values to exclude.
   *
   * @param enumClass enum class to return random element from
   * @param excludes values to exclude
   * @param  the type of the given enum class
   * @return random element from the given enum class that's not in the values to exclude.
   * @throws IllegalArgumentException if the given enumClass has no values
   */
  public static > T random(Class enumClass, Collection excludes) {
    EnumSet enums = EnumSet.allOf(enumClass);
    return IterableUtils.randomFrom(enums, excludes);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy