summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java
blob: 61b13ead91d3cd4443637f05972112f781e2c028 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package bjc.utils.funcutils;

import java.util.Random;
import java.util.function.Consumer;

import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.IList;

/**
 * Utility methods on enums
 * 
 * @author ben
 *
 */
public class EnumUtils {
	/**
	 * Do an action for a random number of enum values
	 * 
	 * @param <E>
	 *            The type of the enum
	 * @param enumClass
	 *            The enum class
	 * @param nValues
	 *            The number of values to execute the action on
	 * @param action
	 *            The action to perform on random values
	 * @param rnd
	 *            The source of randomness to use
	 */
	public static <E extends Enum<E>> void doForValues(Class<E> enumClass,
			int nValues, Consumer<E> action, Random rnd) {
		E[] enumValues = enumClass.getEnumConstants();

		IList<E> valueList = new FunctionalList<>(enumValues);

		int randomValueCount = enumValues.length - nValues;

		for (int i = 0; i <= randomValueCount; i++) {
			E rDir = valueList.randItem(rnd::nextInt);

			valueList.removeMatching(rDir);
		}

		valueList.forEach(action);
	}

	/**
	 * Get a random value from an enum
	 * 
	 * @param <E>
	 *            The type of the enum
	 * @param enumClass
	 *            The class of the enum
	 * @param rnd
	 *            The random source to use
	 * @return A random value from the specified enum
	 */
	public static <E extends Enum<E>> E getRandomValue(Class<E> enumClass,
			Random rnd) {
		E[] enumValues = enumClass.getEnumConstants();

		return new FunctionalList<>(enumValues).randItem(rnd::nextInt);
	}
}