Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Weekday from int

Tags:

java

enums

I have this enum

public enum Weekday {
    Sunday(0), Monday(1), Tuesday(2), Wednesday(3), Thursday(4), Friday(5), Saturday(6);
    private int value;

    private Weekday(int value) {
        this.value = value;
    }



}

And I can get the value from the day if I know what day I want, and I am having a brain freeze right now and am trying to do the oppostie. And cant figure it out

So I know I have number 2 and then want to return a variable of Weekday type Tuesday?

How can I do this?

Thanks for the help :)

like image 656
iqueqiorio Avatar asked Dec 14 '25 09:12

iqueqiorio


2 Answers

You can use Map and then create a method like getByCode, where you will pass the day number as the argument and it will return you the enum. E.g.

import java.util.HashMap;
import java.util.Map;

enum Weekday {
    Sunday(0), Monday(1), Tuesday(2), Wednesday(3), Thursday(4), Friday(5), Saturday(6);
      private int value;

      Weekday(int c){
         this.value =c;
      }


      static Map<Integer, Weekday> map = new HashMap<>();

      static {
         for (Weekday catalog : Weekday.values()) {
            map.put(catalog.value, catalog);
         }
      }

      public static Weekday getByCode(int code) {
         return map.get(code);
      }
   }

You can call the above method like Weekday.getByCode(2) and it will return you Tuesday

like image 148
sol4me Avatar answered Dec 16 '25 05:12

sol4me


Weekday.values() returns an array with all enum values. Each enum value has a method ordinal(), which returns it's index in the enum declaration.

In this case, where the value is equal to the index, you can simplify your code:

public enum Weekday {
    Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}

Get the value:

Weekday.Sunday.ordinal()

Get the enum value:

Weekday.values()[value]
like image 40
Markus Patt Avatar answered Dec 16 '25 05:12

Markus Patt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!