【问题标题】:Mapping String to String value将字符串映射到字符串值
【发布时间】:2012-08-21 18:35:03
【问题描述】:

这是我的问题:

我有可能的Product 类别列表(例如:ShoesModeWomen),我需要将其转换为我的具体名称。

示例:我得到类别Women,我需要将其转换为Lady's

我有大约 40 个类别名称需要转换。

我的问题是:在 JAVA 中最好的方法是什么。

我考虑过switch case,但我不知道这是一个好的解决方案。

switch (oldCategoryName) {
    case "Women":
        return "Ladys";
    default:
        return "Default";
}

【问题讨论】:

    标签: java string converter


    【解决方案1】:

    您可以为此使用静态地图。 制作如下静态地图

    public class PropertiesUtil {
        private static final Map<String, String> myMap;
        static {
            Map<String, String> aMap = new HashMap<String, String>();
            aMap.put("Women", "Ladys");
            aMap.put("another", "anotherprop");
            myMap = Collections.unmodifiableMap(aMap);
        }
    }
    

    然后获取替换字符串..

    String womenReplace = PropertiesUtil.myMap.get("Women");
    

    【讨论】:

      【解决方案2】:

      你也可以考虑使用枚举:

       public enum ProductsCategory {
              Mode("MyMode"),
              Shoes("MyShoes"); 
      
              private String name;
      
              private ProductsCategory(String name) {
                  this.name = name;
              }
      
              public String getName() {
                  return name;
              }
          }
      

      然后检索:

      String myModeStr = ProductsCategory.Mode.getName();
      

      【讨论】:

      • 非常感谢,我可能会选择属性文件解决方案。添加新类别和进行更改最容易
      【解决方案3】:

      请注意,对于低于 7 的 java 版本,java switch 不适用于 String 对象。

      您可以将值存储在地图中:

      // storing
      Map<String, String> map = new HashMap<String, String>();
      map.put("Women", "Ladys");
      // add other values
      
      // retrieving
      String ladys = map.get("Women");
      

      或者您也可以使用.properties 文件来存储所有这些关联,并检索属性对象。

      InputStream in = new FileInputStream(new File("mapping.properties"));
      Properties props = new Properties();
      props.load(in);
      in.close();
      String ladys = props.getProperty("Women");
      

      【讨论】:

      • 非常感谢,我可能会选择属性文件解决方案。添加新类别和进行更改最容易
      • 不客气。如果答案有用,您可以投票/接受。
      猜你喜欢
      • 2018-07-09
      • 2021-01-15
      • 2021-11-09
      • 2019-06-09
      • 1970-01-01
      • 2012-01-23
      • 2021-11-15
      • 1970-01-01
      • 2019-07-03
      相关资源
      最近更新 更多