2

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

3 Answers 3

3

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");
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Many thanks, i will probably go with the property file solution. Its easiest to add new categories and make changes
0

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

1 Comment

Many thanks, i will probably go with the property file solution. Its easiest to add new categories and make changes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.