Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over an enum by its int value?

Tags:

java

enums

I have an assignment to write an Enum "Weekdays" which constants are with more than one parameters.

Does the Enum type has a short way to iterate over its values by their property (1,2,3,4,5,6,7 - from my code) or I have to write another data type where to store the requested data?
That's my code:

public enum Weekdays {
    MON("Monday", "Mon",1),
    TUE("Tuesday","Tue",2),
    WED("Wednesday","Wed",3),
    THU("Thursday","Thu",4),
    FRI("Friday", "Fri",5),
    SAT("Saturday","Sat",6),
    SUN("Sunday","Sun",7);

     private String fullName;
     private String shortName;
     private int number;

    Weekdays(String fullName, String shortName, int number) {
        this.fullName = fullName;
        this.shortName = shortName;
        this.number = number;
    }

    public String getFullName() {
        return fullName;
    }

    public String getShortName() {
        return shortName;
    }

    public int getNumber() {
        return number;
    }
 }

The problem is that the code has to iterate over a value which is set by the user, so I cannot just iterate over the enum from its start to the end.

Edit because I think I don't explain it well:
The code has to iterate over a int value entered by the user and to print another constant's property- for example: when the user's input is 4, the program should print:

Thursday, Friday, Saturday, Sunday, Monday, Thuesday, Wednesday 
like image 523
Savina Dimitrova Avatar asked Oct 29 '22 07:10

Savina Dimitrova


1 Answers

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());
    }
}
like image 73
Andrew Tobilko Avatar answered Nov 15 '22 06:11

Andrew Tobilko