tags:

views:

158

answers:

2

My string looks like;

String values = "I am from UK, and you are from FR";

and my hashtable;

Hashtable countries = new Hashtable();
countries.put("United Kingdom", new String("UK"));
countries.put("France", new String("FR"));

What would be the most effective way to change the values in my string with the values from the hashtable accordingly. These are just 2 values to change, but in my case I will have 100+

+5  A: 

I'm not sure there's a whole lot you can do to optimize this in a way which is worthwhile. Actually you can construct an FSM for custom replacements like that but it's probably more than you want to really do.

Map<String, String> countries = new HashMap<String, String>();
countries.put("United Kingdom", "UK");
countries.put("France", "FR");
for (Map.Entry<String, String> entry : countries.entrySet()) {
  values.replace(entry.getKey(), entry.getValue());
}

A couple of notes:

  1. Don't use Hashtable. Use a Map (interface) and HashMap (class) instead;

  2. Declare your variable, parameter and return types, where applicable, as interfaces not concrete classes;

  3. Assuming you're using Java 5, use generic type arguments for more readable code. In this case, Map<String, String>, etc; and

  4. Don't use new String("UK"). There is no need.

cletus
Thank you very much @cletus for your tips.
Adnan
In this case, it should be `values.replace(entry.getValue(), entry.getKey())` because short names are values in the map. Although I don't know why it is so.
abhin4v
what's an FSM? (Google finds this: http://en.wikipedia.org/wiki/Flying_Spaghetti_Monster) :-)
seanizer
Finite state machine?
c0mrade
that's what I thought, but I didn't see the relevance here...
seanizer
+2  A: 

Several thoughts. First of all: why use hashtable? hashmap is usually faster as hashtable is synchronized.

Then: why not use generics?

HashMap<String, String>

is much more expressive than just HashMap

Third: don't use new String("UK"), "UK" will do fine, you're creating the same string twice.

But to solve your problem, you probably want to turn the map around:

Map<String,String> countries = new HashMap<String, String>();
countries.put("UK", "United Kingdom");
countries.put("FR", "France");

Now if I understand you right you want to do something like this:

String values = "I am from UK, and you are from FR";
for(Map.Entry<String, String> entry : countries.entrySet()){
    values = values.replace(entry.getKey(), entry.getValue());
}
seanizer