Java Data Type How to - Loop through "Color" enum and printing values. Different ways of doing it








Question

We would like to know how to loop through "Color" enum and printing values. Different ways of doing it.

Answer

import java.awt.Color;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
/*from w  w  w  .j  a v  a  2  s . co  m*/
public class Main {
  public static void main(String[] args) throws IllegalAccessException {
    Class clazz = Color.class;
    Field[] colorFields = clazz.getDeclaredFields();

    HashMap<String, Color> singleColors = new HashMap<String, Color>();
    for (Field cf : colorFields) {
      int modifiers = cf.getModifiers();
      if (!Modifier.isPublic(modifiers))
        continue;

      Color c = (Color) cf.get(null);
      if (!singleColors.values().contains(c))
        singleColors.put(cf.getName(), c);
    }

    for (String k : singleColors.keySet()) {
      System.out.println(k + ": " + singleColors.get(k));
    }
  }
}

The code above generates the following result.