gpt4 book ai didi

java - 获取单词频率的更有效方法

转载 作者:行者123 更新时间:2023-11-29 09:48:51 27 4
gpt4 key购买 nike

我想通过单词的开头来计算 ArrayList 中每个单词的出现频率。例如 [cat, cog, mouse] 表示有 2 个以 c 开头的单词和一个以 m 开头的单词。我的代码工作正常,但字母表中有 26 个字母,需要更多的 if 。还有其他方法吗?

public static void  countAlphabeticalWords(ArrayList<String> arrayList) throws IOException
{
int counta =0, countb=0, countc=0, countd=0,counte=0;
String word = "";
for(int i = 0; i<arrayList.size();i++)
{

word = arrayList.get(i);

if (word.charAt(0) == 'a' || word.charAt(0) == 'A'){ counta++;}
if (word.charAt(0) == 'b' || word.charAt(0) == 'B'){ countb++;}

}
System.out.println("The number of words begining with A are: " + counta);
System.out.println("The number of words begining with B are: " + countb);

}

最佳答案

使用 map

public static void  countAlphabeticalWords(List<String> arrayList) throws IOException {
Map<Character,Integer> counts = new HashMap<Character,Integer>();
String word = "";

for(String word : list) {
Character c = Character.toUpperCase(word.charAt(0));
if (counts.containsKey(c)) {
counts.put(c, counts.get(c) + 1);
}
else {
counts.put(c, 1);
}
}

for (Map.Entry<Character, Integer> entry : counts.entrySet()) {
System.out.println("The number of words begining with " + entry.getKey() + " are: " + entry.getValue());
}

或者使用 Map 和 AtomicInteger(根据 Jarrod Roberson)

public static void  countAlphabeticalWords(List<String> arrayList) throws IOException {
Map<Character,AtomicInteger> counts = new HashMap<Character,AtomicInteger>();
String word = "";

for(String word : list) {
Character c = Character.toUpperCase(word.charAt(0));
if (counts.containsKey(c)) {
counts.get(c).incrementAndGet();
}
else {
counts.put(c, new AtomicInteger(1));
}
}

for (Map.Entry<Character, AtomicInteger> entry : counts.entrySet()) {
System.out.println("The number of words begining with " + entry.getKey() + " are: " + entry.getValue());
}

最佳实践

切勿使用 list.get(i),而应使用 for(element : list)。永远不要在签名中使用 ArrayList,而是使用接口(interface) List,这样您就可以更改实现。

关于java - 获取单词频率的更有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15721890/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com