replace values in a String from a Hashtable in Java
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开发者_Go百科 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+
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:
Don't use
Hashtable
. Use aMap
(interface) andHashMap
(class) instead;Declare your variable, parameter and return types, where applicable, as interfaces not concrete classes;
Assuming you're using Java 5, use generic type arguments for more readable code. In this case,
Map<String, String>
, etc; andDon't use
new String("UK")
. There is no need.
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());
}
精彩评论