从Java中的Hashtable替换String中的值

Adn*_*nan 1 java hashtable

我的字符串看起来像;

String values = "I am from UK, and you are from FR";
Run Code Online (Sandbox Code Playgroud)

和我的哈希表;

Hashtable countries = new Hashtable();
countries.put("United Kingdom", new String("UK"));
countries.put("France", new String("FR"));
Run Code Online (Sandbox Code Playgroud)

使用哈希表中的值相应地更改字符串中的值的最有效方法是什么.这些只是改变的2个值,但在我的情况下,我将有100+

cle*_*tus 5

我不确定你能做多少事情以一种值得的方式来优化它.实际上你可以为这样的自定义替换构建一个FSM,但它可能比你想要的更多.

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());
}
Run Code Online (Sandbox Code Playgroud)

几个笔记:

  1. 不要用Hashtable.使用Map(接口)和HashMap(类)代替;

  2. 声明你的变量,参数和返回类型,如果适用,作为接口而不是具体类;

  3. 假设您使用的是Java 5,请使用泛型类型参数来获得更易读的代码.在这种情况下Map<String, String>,等; 和

  4. 不要用new String("UK").没有必要.