21

Let's say I have an enum like so:

public enum Numbers {
    ONE("Uno "),
    TWO("Dos "),
    THREE("Tres ");
}

private final String spanishName;

Numbers(String spanishName) {
    this.spanishName = spanishName;
}

public String getSpanishName() {
    return spanishName;
}

Now I have a method that outputs a given variable.

public void output(String value) {
    printStream.print(value);
}

I want to use a for loop to output all the values in the enum. Something along the lines of this:

for(/*each element in the enum*/) {
    //output the corresponding spanish name
}

Ultimate I want the final output to be Uno Dos Tres. How can I do this using enums and a for loop?

Charles
  • 4,372
  • 9
  • 41
  • 80
  • @RaviThapliyal You won't find '.values()' under Enum in the JavaDocs. It's an implicit method for enum type. – NominSim May 21 '13 at 16:33

3 Answers3

44
for (Numbers n : Numbers.values()) {
   System.out.print(n.getSpanishName() + " ");
}
ktm5124
  • 11,861
  • 21
  • 74
  • 119
7

Use this:

for (Numbers d : Numbers .values()) {
     System.out.println(d);
 }
Lokesh
  • 7,810
  • 6
  • 48
  • 78
5
for (Numbers num : Numbers.values()) {
  // do what you want
}

looks like duplicate: A 'for' loop to iterate over an enum in Java

Community
  • 1
  • 1
Dory Zidon
  • 10,497
  • 2
  • 25
  • 39