私は、列挙型の内部値の間をマッピングすることはできますか?

chronos14:

ブランド名と銘柄コード:私は2つの値を持つ列挙型を作成します。
私はブランド名を入力することで、ブランドのコードを知りたいです。
そして、私はまた、銘柄コードを入力することにより、ブランド名を知りたいです。
この問題は、列挙型を使用して解決することはできますか?または他のコードは、より有効なのでしょうか?私はできるだけ短いようなコードを作成したいです

私は、ブランドのコードを検索するには、次のコードを作成しました。私はその逆を行いたい場合は、私はブランドにコードを変換するために、ハッシュマップと方法別のものを作成することができます。しかし、それはそれを解決するための効果的な方法は何ですか?

public enum Brand{
  COLA("cola", "CL8935"),
  BREAD("bread", "BR2810"),
  SNICKERS("snickers", "SN4423");

  private static final Map<String, String> BY_BRAND = new HashMap<>();

  static {
    for (Brand brand : values()){
       BY_BRAND.put(brand.code, brand.brand);
    }
  }

  private final String brand;
  private final String code;

  public static String convertToCode(String brand){
    return BY_BRAND.get(brand.toLowerCase()).toString();
  } 
}
Vivic:

更新 - (輸入品との)完全な列挙型を追加

import java.util.Arrays;
import java.util.function.Function;

enum Brand {

   COLA("cola", "CL8935"),
   BREAD("bread", "BR2810"),
   SNICKERS("snickers", "SN4423");

   private final String brand;

   private final String code;

   Brand(String brand, String code) {
      this.brand = brand;
      this.code = code;
   }

   public static Brand findBy(String value, Function<Brand, String> extractor) {
      return Arrays.stream(Brand.values())
            .filter(brand -> extractor.apply(brand).equalsIgnoreCase(value))
            .findFirst()
            .orElse("Either a default or throw exception here");
   }

   public String getBrand() {
      return brand;
   }

   public String getCode() {
      return code;
   }

}

元の

あなたは、マップの代替として、静的findByメソッドを使用することができます。これは、あなたが列挙内に格納された値を比較するために使用されるゲッターの値および方法を参照して渡すことができるようになります。

ここでの違いは、(マップがより速くなるように)、性能、あなたが列挙型を返すと、あなたが最も可能性のいずれかのデフォルト列挙値たい、あるいは全くマッチしているFOUNDに例外をスローするということでしょうということになります。以下は一例です

 public static Brand findBy(String value, Function<Brand, String> extractor) {
      return Arrays.stream(Brand.values())
            .filter(brand -> extractor.apply(brand).equalsIgnoreCase(value))
            .findFirst()
            .orElse("Either a default or throw exception here");
   }

そして、これは次のように呼び出すことができます

public static void main(String[] args) {
      Brand brand1 = Brand.findBy("cola", Brand::getBrand);
      Brand brand2 = Brand.findBy("BR2810", Brand::getCode);
   }

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=231877&siteId=1