user739115
user739115

Reputation: 1217

replace string with map value with if key is match with exact string

Map<String, String> hashtable = new Hashtable<>();
hashtable.put("eBook Cover Image", "724242");
hashtable.put("Cover Image", "95757");
hashtable.put("Image", "9242424");
hashtable.put("Composite", "7697979");
hashtable.put("Low-Res PDF (print)", "1111111111111111");
hashtable.put("Cover", "c11111111");

String s = "eBook Cover Image OR (Low-Res PDF (print) AND Composite)";

for (Map.Entry<String, String> m : hashtable.entrySet()) {
    s = s.replace(m.getKey(), m.getValue());
}

replacing is not happening properly.

eBook c11111111 9242424 OR (1111111111111111 AND pppppppppppppppp)

Upvotes: 0

Views: 357

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075587

The order in which the entries are iterated is not set with Hashtable, so it looks like you're visiting "Image" before visiting "eBook Cover Image".

You probably want a LinkedHashMap where you put the longer keys in the map first (as you have in your example), because it will iterate the entries in insertion order (by default).

Upvotes: 5

Related Questions