File tree Expand file tree Collapse file tree
core-java-modules/core-java-lang-2/src
main/java/com/baeldung/inttoenum
test/java/com/baeldung/inttoenum Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .inttoenum ;
2+
3+ import java .util .HashMap ;
4+ import java .util .Map ;
5+
6+ public enum PizzaStatus {
7+ ORDERED (5 ),
8+ READY (2 ),
9+ DELIVERED (0 );
10+
11+ private int timeToDelivery ;
12+
13+ PizzaStatus (int timeToDelivery ) {
14+ this .timeToDelivery = timeToDelivery ;
15+ }
16+
17+ public int getTimeToDelivery () {
18+ return timeToDelivery ;
19+ }
20+
21+ private static Map <Integer , PizzaStatus > timeToDeliveryToEnumValuesMapping = new HashMap <>();
22+
23+ static {
24+ PizzaStatus [] pizzaStatuses = PizzaStatus .values ();
25+ for (int pizzaStatusIndex = 0 ; pizzaStatusIndex < pizzaStatuses .length ; pizzaStatusIndex ++) {
26+ timeToDeliveryToEnumValuesMapping .put (
27+ pizzaStatuses [pizzaStatusIndex ].getTimeToDelivery (),
28+ pizzaStatuses [pizzaStatusIndex ]
29+ );
30+ }
31+ }
32+
33+ public static PizzaStatus castIntToEnum (int timeToDelivery ) {
34+ return timeToDeliveryToEnumValuesMapping .get (timeToDelivery );
35+ }
36+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .inttoenum ;
2+
3+ import org .junit .Test ;
4+
5+ import static org .junit .Assert .assertEquals ;
6+
7+ public class IntToEnumUnitTest {
8+
9+ @ Test
10+ public void whenIntToEnumUsingValuesMethod_thenReturnEnumObject () {
11+ int timeToDeliveryForOrderedPizzaStatus = 5 ;
12+ PizzaStatus [] pizzaStatuses = PizzaStatus .values ();
13+ PizzaStatus pizzaOrderedStatus = null ;
14+ for (int pizzaStatusIndex = 0 ; pizzaStatusIndex < pizzaStatuses .length ; pizzaStatusIndex ++) {
15+ if (pizzaStatuses [pizzaStatusIndex ].getTimeToDelivery () == timeToDeliveryForOrderedPizzaStatus ) {
16+ pizzaOrderedStatus = pizzaStatuses [pizzaStatusIndex ];
17+ }
18+ }
19+ assertEquals (pizzaOrderedStatus , PizzaStatus .ORDERED );
20+ }
21+
22+ @ Test
23+ public void whenIntToEnumUsingMap_thenReturnEnumObject () {
24+ int timeToDeliveryForOrderedPizzaStatus = 5 ;
25+ assertEquals (PizzaStatus .castIntToEnum (timeToDeliveryForOrderedPizzaStatus ), PizzaStatus .ORDERED );
26+ }
27+ }
You can’t perform that action at this time.
0 commit comments