A For-Loop to Iterate Over an Enum in Java

A for-loop to iterate over an enum in Java

.values()

You can call the values() method on your enum.

for (Direction dir : Direction.values()) {
// do what you want
}

This values() method is implicitly declared by the compiler. So it is not listed on Enum doc.

How do I loop through an enum in Java?

for (Numbers n : Numbers.values()) {
System.out.print(n.getSpanishName() + " ");
}

Iterate over all the values of enum in the order of decreasing value.

I think that the best way is to create Comparator implementation and use it to sort values.
You can define inverse comparator as follows:

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class MyClass {
public static void main(String args[]) {
List<HardCurrency> hardCurrencies = Arrays.asList(HardCurrency.values());
Collections.sort(hardCurrencies, new HardCurrencyInverseComparator());
for (HardCurrency hc : hardCurrencies) {
System.out.println(hc.getValue());
}
}

enum HardCurrency {
ONE(1), FIVE(5), TEN(10), TWENTY(20), FIFTY(50), HUNDRED(100), FIVE_HUNDRED(
500), TWO_THOUSAND(2000);

private final BigDecimal value;

HardCurrency(int value) {
this.value = new BigDecimal(value);
}

public BigDecimal getValue() {
return value;
}

}

static class HardCurrencyInverseComparator implements Comparator<HardCurrency> {

public int compare(HardCurrency currency1, HardCurrency currency2) {
return currency2.getValue().compareTo(currency1.getValue());
}

}

}

How to iterate over an enum that has custom values?

Use a stream to map an array of enum values to a list of strings.

List<String> exercises = Stream.of(DaysOfExercise.values())
.map(DaysOfExercise::getExercise)
.collect(Collectors.toList());

How to iterate over an enum by its int value?

You could get all enum values by values() and map them to a Weekdays::getNumber filtering values that are lower than the userInput:

Arrays.stream(Weekdays.values())
.mapToInt(Weekdays::getNumber)
.filter(i -> i > userInput)
.forEach(i -> { /**/ });

For efficiency, you also could hold the mapped array in a static field:

private static int[] numbers = Arrays.stream(Weekdays.values()).mapToInt(Weekdays::getNumber).toArray();

and use that when it needs:

public void method(int userInput) {
// validate userInput
for (int i = userInput; i < numbers.length; i++) {
// do sth with numbers[i]
}
}

EDIT:

I caught your requirements in the comment, here is the solution as I see it:

public void method(int userInput) {
// validate userInput
Weekdays[] values = Weekdays.values();

for (int i = userInput; i < values.length + userInput; ++i) {
Weekdays day = values[i % values.length];
System.out.println(day.getFullName());
}
}

Enum type in Java : values() in for each loop

The values() method returns an array of enum values. In Java you can iterate over array using for(Object obj : arr) syntax. It's just a syntactic sugar. During the compilation the implicit int local variable will be created and the cycle will be rewritten like this:

Planet[] vals = Planet.values();
for(int i=0; i<vals.length; i++) {
Planet p = vals[i];
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}

Iterate over enums (the class objects) with shared interface in Java

Reflection only makes sense if you do not already know the enums
(i.e. you have to discover the enums in a package).

If you already know the enums,
then a variation of your code is reasonable.

For example:

public List<Word> allWords()
{
List<Word> returnValue = new LinkedList<>();
returnValue.addAll(Arrays.asList(Article.values()));
returnValue.addAll(Arrays.asList(Conjunction.values()));
returnValue.addAll(Arrays.asList(Verb.values()));
// And so on...
return returnValue;
}

I suggest a List. because the Set will remove duplicates by name.

Edit:
My List suggestion now seems unnecessary.

Edit2:
Per comment,
set is not as bad as I want to believe it.
Still,
you are using the collection as a "list of junk",
I suggest List is the better choice.

Looping through enum values without enhanced for loop

The values() method of an enum returns an array. If you want to iterate through an array with a normal for loop, it would look like this:

AnotherClass.Colors[] values = AnotherClass.Colors.values();
for (int i = 0; i < values.length; ++i) {
System.out.println(values[i]);
}

Enhanced for loops and enums were both introduced in Java 1.5, so the enhanced for loop has always been the obvious way to iterate through enum values.



Related Topics



Leave a reply



Submit