Java 对列表中的单词进行计数,并将它们及其计数保存在Hashmap中
我有一个名为words的列表实例和一个名为map的HashMap实例。我在列表中有一些单词,并将它们数出来保存在HashMap上。HashMap将count作为值,将word作为键 我不知道我做错了什么。非常感谢您的帮助 是否有更好的实施方案Java 对列表中的单词进行计数,并将它们及其计数保存在Hashmap中,java,hashmap,word-count,Java,Hashmap,Word Count,我有一个名为words的列表实例和一个名为map的HashMap实例。我在列表中有一些单词,并将它们数出来保存在HashMap上。HashMap将count作为值,将word作为键 我不知道我做错了什么。非常感谢您的帮助 是否有更好的实施方案 始终输入My else子句。您在每次迭代中创建一个新映射。您应该将映射初始化移动到循环之前。您正在每个迭代中创建一个新映射。您应该将映射初始化移动到循环之前。是的,这是因为您为每个单词实例化了一个新的HashMap: for (String aword :
始终输入My else子句。您在每次迭代中创建一个新映射。您应该将映射初始化移动到循环之前。您正在每个迭代中创建一个新映射。您应该将映射初始化移动到循环之前。是的,这是因为您为每个单词实例化了一个新的HashMap:
for (String aword : words) {
map = new HashMap<String, Integer>(); // <- here
...
将其移出循环:
map = new HashMap<String, Integer>();
for (String aword : words) {
if (map.containsKey(aword)) {
...
是的,这是因为您为每个单词实例化了一个新的HashMap:
for (String aword : words) {
map = new HashMap<String, Integer>(); // <- here
...
将其移出循环:
map = new HashMap<String, Integer>();
for (String aword : words) {
if (map.containsKey(aword)) {
...
在for循环外部创建映射
map = new HashMap<String, Integer>();
for (String aword : words) {
if (map.containsKey(aword)) {
int count;
try {
count = map.get(aword);
count++;
} catch (NullPointerException npe) {
count = 0;
}
map.put(aword, count);
System.out.println(aword+"SS"+count);
} else {
map.put(aword, 0);
System.out.println(aword+"else"+0);
}
}
在for循环外部创建映射
map = new HashMap<String, Integer>();
for (String aword : words) {
if (map.containsKey(aword)) {
int count;
try {
count = map.get(aword);
count++;
} catch (NullPointerException npe) {
count = 0;
}
map.put(aword, count);
System.out.println(aword+"SS"+count);
} else {
map.put(aword, 0);
System.out.println(aword+"else"+0);
}
}
我不使用containsKey然后get然后put,而是这样做:
map = new HashMap<String, Integer>(); //put it here instead than in the for loop
for (String aword : words) {
Integer tmp = stats.put(word, 1); //tmp is the previous value associated with key "word"
if (tmp != null) {
stats.put(word, ++tmp);
}
}
我不使用containsKey然后get然后put,而是这样做:
map = new HashMap<String, Integer>(); //put it here instead than in the for loop
for (String aword : words) {
Integer tmp = stats.put(word, 1); //tmp is the previous value associated with key "word"
if (tmp != null) {
stats.put(word, ++tmp);
}
}
在循环外部创建映射并删除try catch
Map<String, Integer> map = new HashMap<>();
for (String word : words) {
int count = map.containsKey(word) ? map.get(word) : 0;
map.put(word, count + 1);
}
在循环外部创建映射并删除try catch
Map<String, Integer> map = new HashMap<>();
for (String word : words) {
int count = map.containsKey(word) ? map.get(word) : 0;
map.put(word, count + 1);
}
@Nabin我想这是一种更短、更有效的方法,因为你可以避免对映射进行过多的迭代。@Nabin我想这是一种更短、更有效的方法,因为你可以避免对映射进行过多的迭代。@Nabin,我不明白你为什么需要捕捉NullPointerException,因为你在从地图上获取计数之前先检查了存在。还有别的吗?这是做这项工作的最佳代码吗?高效?@Nabin看起来不错,除了你需要的一点改变,当找不到单词时,将计数初始化为1,而不是0。谢谢。我已经发现了一次,我可以运行代码了,非常感谢。@Nabin,我不明白你为什么需要捕获NullPointerException,因为你在从地图中获取计数之前先检查是否存在。还有什么吗?这是做这项工作的最佳代码吗?高效?@Nabin看起来不错,除了你需要的一点改变,当找不到单词时,将计数初始化为1,而不是0。谢谢。我已经发现了,我可以运行代码了,非常感谢。