如何在单词上使用 split(" ") 实例化地图,并遍历生成的数组。 * 在生成的 for 循环中,每次遇到映射中还不是键的词时,都应向映射插入一个新键,每次遇到映射中已存在的词时,都应将其添加到词的计数值中地图。
Map<String, Integer> map = new Hash Map<String, Integer>();
for (String s : string Array) {
if (containerization(s)) {
map.put(s, map.get(s) + 1);
} else {
map.put(s, 1);
}
}
return map;
}
}
您可能要根据描述编写的代码:
class Main {
public static void main(String[] args) {
String input = "Hello world Hello all";
Map<String, Integer> wordMap = countWords(input);
System.out.println(wordMap); // {all=1, world=1, Hello=2}
}
private static HashMap<String, Integer> countWords(final String text) {
HashMap<String, Integer> wordMap = new HashMap<>();
String[] words = text.split(" "); // split the input string by space
for (String word : words) {
if (wordMap.containsKey(word)) {
wordMap.put(word, wordMap.get(word) + 1); // increment count of existing word
} else {
wordMap.put(word, 1); // add new word to the map
}
}
return wordMap;
}
}
注意可以这样改进:
class Main {
public static void main(String[] args) {
String input = "Hello world Hello all";
Map<String, Integer> wordMap = countWords(input);
System.out.println(wordMap); // {all=1, world=1, Hello=2}
}
private static HashMap<String, Integer> countWords(final String text) {
HashMap<String, Integer> wordMap = new HashMap<>();
String[] words = text.split(" "); // split the input string by space
for (String word : words) {
wordMap.merge(word, 1, Integer::sum);
}
return wordMap;
}
}
或者那样:
class Main {
public static void main(String[] args) {
String input = "Hello world Hello all";
Map<String, Integer> wordMap = countWords(input);
System.out.println(wordMap); // {all=1, world=1, Hello=2}
}
private static Map<String, Integer> countWords(final String text) {
return Arrays.stream(text.split(" "))
.collect(groupingBy(identity(), summingInt(x -> 1)));
}
}
还有一种方法。使用Map.merge.
Map<String, Integer> map = new HashMap<String, Integer>();
String s = "one three five four four"
+ " two three five four four"
+ " five five three two five";
\\s+
- 在一个或多个空白字符处拆分
for (String word : s.split("\\s+")) {
map.merge(word, 1, Integer::sum);
}
map.entrySet().forEach(System.out::println);
版画
four=4
one=1
two=2
five=5
three=3