[英]Mapping String to String value
這是我的問題:
我有可能的Product
類別列表(例如: Shoes
, Mode
, Women
),我需要將其轉換為我的特定名稱。
示例:我得到了類別Women
,我需要將其轉換為Lady's
。
我大約需要轉換40個類別名稱。
我的問題是:在JAVA中最好的方法是什么?
我想到了開關盒,但我不知道這是一個好的解決方案。
switch (oldCategoryName) {
case "Women":
return "Ladys";
default:
return "Default";
}
您可以為此使用靜態地圖。 制作如下的靜態地圖
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");
您還可以考慮使用枚舉:
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();
請注意,對於低於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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.