How to iterate over an enum by its int value?

I have a task to write Enum "Weekdays", the constants of which consist of several parameters. Does the Enum type have a short way to iterate over its values ​​by their property (1,2,3,4,5,6,7 - from my code), or do I need to write another data type where to store the requested data?
What is 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 must iterate over the value set by the user, so I cannot just iterate over the enumeration from the very beginning to the end.

Change, because I think I am not explaining it well:
The code should iterate over the int value entered by the user and print another property of the constant - for example: when the user input is 4, the program should print:

 Thursday, Friday, Saturday, Sunday, Monday, Thuesday, Wednesday 
+5
source share
1 answer

You can get all the enumeration values() on values() and map them to the Weekdays::getNumber filter values ​​that are lower than userInput :

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

For efficiency, you can also hold the matched array in a static field:

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

and use this when needed:

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

EDIT:
I understood your requirements in a comment, here is the solution I see:

 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()); } } 
+2
source

Source: https://habr.com/ru/post/1268302/


All Articles