我使用HashMap存储缩写的完整表单.
public class Test { public static void main(String[] args) { Mapslangs = new HashMap (); slangs.put("lol", "laugh out loud"); slangs.put("r", " are "); slangs.put("n", " and "); slangs.put("idk", " I don't know "); slangs.put("u", " you "); Set set = slangs.entrySet(); Iterator i = set.iterator(); String sentence = "lol how are you"; StringBuilder sb = new StringBuilder(); for (String word : sentence.split(" ")) { while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); if (word.equalsIgnoreCase(me.getKey())) { sb.append(me.getValue()); continue; } sb.append(word); } } System.out.println(sb.toString()); } }
输出是:
lollollollaugh out loudlol
这里有什么问题,如何解决?
你不应该来遍历条目找到匹配,你应该使用get(Object key)
或getOrDefault(Object key, V defaultValue)
得到一个给定的缩写的完整形式,否则,而不是让你充满形式的时间复杂度O(1)
,你会用得到它O(n)
这在表演方面当然不是很好,你会失去把你的键/值对放在一起的真正好处Map
.如果您因为这种情况而这样做,只需将您的密钥仅以小写字母放在地图中并打电话get
或getOrDefault
使用小写字样如下:
所以你的循环应该是这样的:
for (String word : sentence.split(" ")) { // Get the full form of the value of word in lower case otherwise use // the word itself sb.append(slangs.getOrDefault(word.toLowerCase(), String.format(" %s", word))); }
输出:
laugh out loud how are you
使用Stream API,它可能只是:
String result = Pattern.compile(" ") .splitAsStream(sentence) .map(word -> slangs.getOrDefault(word.toLowerCase(), word)) .collect(Collectors.joining(" "));