kozla13
kozla13

Reputation: 1942

Mapping String to String value

Here is my problem:

I have list of possible Product categories(for example: Shoes,Mode,Women), and I need to convert this to my specific names.

example: I get the category Women and I need to convert this to Lady's.

I have about 40 category names that i need to convert.

My question is :What is the best way to do this in JAVA.

I thought about switch case, but i dont know is this a good solution.

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

Upvotes: 2

Views: 144

Answers (3)

kgautron
kgautron

Reputation: 8263

Note that the java switch does not work on String objects for java versions below 7.

You can store values in a map :

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

// retrieving
String ladys = map.get("Women");

Or you can also use a .properties file to store all those associations, and retrieve a property object.

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

Upvotes: 0

dhamibirendra
dhamibirendra

Reputation: 3046

You can use static map for that. Make a Static Map as below

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);
    }
}

then get the replacing string..

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

Upvotes: 3

Lorand Bendig
Lorand Bendig

Reputation: 10650

You can also consider using enums:

 public enum ProductsCategory {
        Mode("MyMode"),
        Shoes("MyShoes"); 

        private String name;

        private ProductsCategory(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }

Then the retrieval:

String myModeStr = ProductsCategory.Mode.getName();

Upvotes: 1

Related Questions