使用HashMap查找字符串中单词出现的Java程序
HashMap
方法 :
- 在Java中声明
的 HashMap - 拆分给定的字符串并将单词存储到 String 数组中。
- 遍历数组,检查单词是否在 HashMap 中。
- 如果不在HashMap中,则将该词存储为key,1为初始值;如果单词存在于 HashMap 中,则增加该单词的值。
- 遍历完成后,打印 HashMap。
例子:
Java
// Java Program to find the occurrence
// of words in a String using HashMap.
import java.io.*;
import java.util.HashMap;
import java.util.Map;
class GFG {
public static void main(String[] args)
{
// Declaring the String
String str = "Alice is girl and Bob is boy";
// Declaring a HashMap of
Map hashMap = new HashMap<>();
// Spliiting the words of string
// and storing them in the array.
String[] words = str.split(" ");
for (String word : words) {
// Asking whether the HashMap contains the
// key or not. Will return null if not.
Integer integer = hashMap.get(word);
if (integer == null)
// Storing the word as key and its
// occrence as value in the HashMap.
hashMap.put(word, 1);
else {
// Incrementing the value if the word
// is already present in the HashMap.
hashMap.put(word, integer + 1);
}
}
System.out.println(hashMap);
}
}
Java
// Java Program to find the occurrence
// of words in a String using HashMap.
import java.io.*;
import java.util.HashMap;
import java.util.Map;
class GFG {
public static void main(String[] args)
{
String str = "Alice is girl and Bob is boy";
Map hashMap = new HashMap<>();
String[] words = str.split(" ");
for (String word : words) {
// containsKey(key) will return a boolean value
// i.e. true if it contains the key and false if
// it doesn't.
if (hashMap.containsKey(word))
hashMap.put(word, hashMap.get(word) + 1);
else
hashMap.put(word, 1);
}
System.out.println(hashMap);
}
}
输出
{Bob=1, Alice=1, and=1, is=2, girl=1, boy=1}
请注意,在上面的代码中,我们使用了 Wrapper 类,即 Integer,因为 get(key) 方法返回 null。
您还可以从上述程序中消除整数变量的使用。
让我们看看下面的代码:
Java
// Java Program to find the occurrence
// of words in a String using HashMap.
import java.io.*;
import java.util.HashMap;
import java.util.Map;
class GFG {
public static void main(String[] args)
{
String str = "Alice is girl and Bob is boy";
Map hashMap = new HashMap<>();
String[] words = str.split(" ");
for (String word : words) {
// containsKey(key) will return a boolean value
// i.e. true if it contains the key and false if
// it doesn't.
if (hashMap.containsKey(word))
hashMap.put(word, hashMap.get(word) + 1);
else
hashMap.put(word, 1);
}
System.out.println(hashMap);
}
}
输出
{Bob=1, Alice=1, and=1, is=2, girl=1, boy=1}