0

I want to assign an int value to strings such that if

"apple" = 1, "banana" = 2

I can do something like

intToStr(1) = "apple"

or

StrToInt("banana") = 2

I know I can do this by using switch statements, but I heard using too many switch statements is not ideal. Would it be okay to use a bunch of switch statements? if not, what would be the best way to do this kind of mapping?

3 Answers3

1

if data is going be a constant, maybe you can use a Enum,

  enum Fruit {
    APPLE, BANANA, STRAWBERRY,
  }

Arrays.stream(Fruit.values()).forEach( fruit -> System.out.println(fruit.name() + " - " + fruit.ordinal()));

output:

APPLE - 0
BANANA - 1
STRAWBERRY - 2

If not, a map will solve your requirement:

Map<String, Integer> fruits = new HashMap<>();

    fruits.put("APPLE", 1);

    fruits.put("BANANA", 2);

    fruits.put("STRAWBERRY", 3);

    fruits.forEach((x,y)->System.out.println(x + " - " + y));

output:

APPLE - 1
BANANA - 2
STRAWBERRY - 3

Source:

admlz635
  • 1,001
  • 1
  • 9
  • 18
0

There are several tools available to solve this problem, depending on the context:

  1. A switch statement as you already suggested.

  2. An enum.

  3. Map<String, Integer>

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

Here are some options.

enum MyEnum {
   Apple(1), Banana(2), Orange(3);
   private int v;

   private MyEnum(int v) {
      this.v = v;
   }

   public int getValue() {
      return v;
   }
}

public class SimpleExample {

   public static void main(String[] args) {
      // You could do it with a Map. Map.of makes an immutable map so if you
      // want to change those values, pass it to a HashMap Constructor

      Map<String, Integer> map = new HashMap<>(Map.of("Apple", 1, "Banana", 2));
      map.entrySet().forEach(System.out::println);

      for (MyEnum e : MyEnum.values()) {
         System.out.println(e + " = " + e.getValue());
      }

   }
}
WJS
  • 36,363
  • 4
  • 24
  • 39