我正在 Java 类(class)中学习 HashMap,并且接到一个任务,将文本文件中的所有单词存储在 HashMap 中,并打印出每个唯一单词及其在文件中出现的次数。
我不知道如何执行此操作,因此在这里搜索帮助并找到此链接:Using HashMap to count instances
我将海报代码改编并使用到我的程序中,它起作用了,但我不完全理解为什么,我不想放弃一些我不明白但我自己没有做的事情。
我已经在下面发布了完整的代码,但是有人可以向我解释一下注释部分的功能吗?
public class Q3HM {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>(50, 10);
*****//Not sure what the (50,10) is for
try {
File input = new File("input.txt");
Scanner read = new Scanner(new FileInputStream(input));
ArrayList<String> list = new ArrayList<>();
while (read.hasNext()) {
list.add(read.next());
}
*******//Not sure how the below for loop works
for (String w : list){
Integer i = map.get(w);
if(i == null){
map.put(w, 1);
}
else {
map.put(w, i+1);
}
}
*******//End of section I'm confused about
System.out.println(map.toString());
}
catch (Exception e){
e.printStackTrace();
}
}
}
最佳答案
for (String w : list) { Integer i = map.get(w); if(i == null) { map.put(w, 1); } else { map.put(w, i+1); } }
对于列表中的每个字符串,
获取旧值并将其存储为 i
。
如果字符串尚未在 map 中(i
为 null
),则插入 1。(第一次出现)
否则,插入 (i + 1)(在当前计数上加一。)
更具描述性的重写可能是
for (String word : list) { //For every word in list,
Integer previousAmount = map.get(word); //Get the current count and store it.
if(previousAmount == null) //If the count doesn't exist (null, not in map),
map.put(word, 1); //Put 1 in the map (first time.)
else //Otherwise (in the map)
map.put(word, previousAmount + 1); //Add one to the current amount
}
这也可以简单地写成
for(String w : list)
map.put(w, map.getOrDefault(w, 0) + 1);
关于java - 文件中 HashMap 字符串出现次数 [JAVA],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41958054/