Java Program to Iterate over enum

JavaObject Oriented ProgrammingProgramming

<p>In this article, we will understand how to iterate over enum objects. Enum is a datatype that represents a small collection of objects.</p><p>Below is a demonstration of the same &minus;</p><p><strong>Input</strong></p><p>Suppose our input is &minus;</p><pre class="result notranslate">Enum objects are defined as : red, blue, green, yellow, orange</pre><p><strong>Output</strong></p><p>The desired output would be &minus;</p><pre class="result notranslate">Printing the Objects: red blue green yellow orange</pre><h2>Algorithm</h2><pre class="result notranslate">Step 1 &ndash; START Step 2 - Declare the objects of Enum function namely red, blue, green, yellow, orange Step 3 &ndash; Using a for loop, iterate over the objects of the enum function and print each object. Step 4- Stop</pre><h2>Example 1</h2><pre class="demo-code notranslate language-java" data-lang="java">enum Enum { red, blue, green, yellow, orange; } public class Colour { public static void main(String[] args) { System.out.println(&quot;The values of Enum function are previously defined .&quot;); System.out.println(&quot;Accessing each enum constants&quot;); for(Enum colours : Enum.values()) { System.out.print(colours + &quot; &quot;); } } }</pre><h2>Output</h2><pre class="result notranslate">The values of Enum function are previously defined . Accessing each enum constants red blue green yellow orange</pre><h2>Example 2</h2><p>Here is an example to print the days of the week.</p><pre class="demo-code notranslate language-java" data-lang="java">import java.util.EnumSet; enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } public class IterateEnum{ public static void main(String args[]) { Days my_days[] = Days.values(); System.out.println(&quot;Values of the enum are: &quot;); EnumSet.allOf(Days.class).forEach(day -&gt; System.out.println(day)); } }</pre><h2>Output</h2><pre class="result notranslate">Values of the enum are: Sunday Monday Tuesday Wednesday Thursday Friday Saturday</pre>
Updated on 21-Feb-2022 12:29:45