How do I pick a random value from an enum?

The following code snippet will show you how to pick a random value from an enum. First we’ll create an enum called BaseColor which will have three valid value. These values are Red, Green and Blue.

To allow us to get random value of this BaseColor enum we define a getRandomColor() method in the enum. This method use the java.util.Random to create a random value. This random value then will be used to pick a random value from the enum.

Let’s see the code snippet below:

package org.kodejava.example.basic;

import java.util.Random;

public class EnumGetRandomValueExample {
    public static void main(String[] args) {
        // Pick a random BaseColor for 10 times.
        for (int i = 0; i < 10; i++) {
            System.out.printf("color[%d] = %s%n", i, 
                    BaseColor.getRandomColor());
        }
    }

    /**
     * BaseColor enum.
     */
    private enum BaseColor {
        Red,
        Green,
        Blue;

        /**
         * Pick a random value of the BaseColor enum.
         * @return a random BaseColor.
         */
        public static BaseColor getRandomColor() {
            Random random = new Random();
            return values()[random.nextInt(values().length)];
        }
    }
}

The output of the code snippet:

color[0] = Blue
color[1] = Red
color[2] = Red
color[3] = Green
color[4] = Blue
color[5] = Blue
color[6] = Green
color[7] = Red
color[8] = Red
color[9] = Green

6 Comments

  1. Nice generate enums I steal your solution 😀 but is there mistake in return values()[random.nextInt(values().length)];. You have to add BaseColor.values().

    Reply
    • The code should work just fine without using BaseColor class to access the values() method. But I agree that using the class name to access the static method make our code clearer to read.

      Reply
  2. I used the same code but changed it to fit my program. The only problem is that the roles in (roles.getRandomRole), can’t be found? I’ve copied your exact program and I can’t seem to find the problem. Do you have any suggestions?

    for (int i = 0; i < 2; i++) {
        System.out.printf("color[%d] = %s%n", i, roles.getRandomRole());
    }
    
    Reply
  3. Wouldn’t it be better to define the Random object outside the method, so you’re not creating a new instance every single method call?

    Reply
  4. I use my test helper:

    public class CommonTestHelper {
        private final ThreadLocalRandom randomizer = ThreadLocalRandom.current();
    
        public <T extends Enum> Optional<T> randomEnumItem(Class<T> tClass) {
            final var items = tClass.getEnumConstants();
            if (ObjectUtils.isEmpty(items)) {
                return Optional.empty();
            }
            return Optional.of(items[randomizer.nextInt(items.length)]);
        }
    }
    

    Example for JUnit 5:

    class ServiceImplTest {
        private final CommonTestHelper commonTestHelper = new CommonTestHelper();
    
        @Test
        void test() {
            var randomColor = commonTestHelper.randomEnumItem(BaseColor.class).get();
            assertThat(randomColor).isNotNull();
        }
    
        /**
         * BaseColor enum.
         */
        private enum BaseColor {
            Red,
            Green,
            Blue
        }
    }
    
    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.