1

我想通过单词的开头来计算 ArrayList 中每个单词的频率。例如 [cat, cog, mouse] 表示有 2 个以c开头的单词和 1 个以m开头的单词。我的代码工作正常,但字母表中有 26 个字母,如果s需要更多。有没有其他方法可以做到这一点?

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);

}
4

3 回答 3

7

使用地图

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在签名中使用接口,List而是使用接口,以便您可以更改实现。

于 2013-03-30T18:33:33.130 回答
4

这个怎么样?考虑到单词仅以 开头[a-zA-Z]

public static int[] getCount(List<String> arrayList) {
    int[] data = new int[26];
    final int a = (int) 'a';

    for(String s : arrayList) {
        data[((int) Character.toLowerCase(s.charAt(0))) - a]++;
    }

    return data;
}

编辑:

只是出于好奇,我做了一个非常简单的测试,将我的方法和 Steph 的方法与 map 进行比较。列出 236 个项目,10000000 次迭代(不打印结果):我的代码花费了大约 10000 毫秒,而斯蒂芬花费了大约 65000 毫秒。

测试: http: //pastebin.com/HNBgKFRk

资料: http: //pastebin.com/UhCtapZZ

于 2013-03-30T18:33:17.427 回答
0

现在,每个字符都可以转换为整数,表示 ASCII 十进制。比如(int)'a'是97。'z'的ASCII十进制是122。http ://www.asciitable.com/

您可以为字符创建查找表:

int characters = new int[128]

然后在你的算法循环中使用 ASCII 十进制作为索引并增加值:

word = arrayList.get(i);
characters[word.charAt(0)]++;

最后,您可以打印字符的出现:

for (int i = 97; i<=122; i++){
  System.out.println(String.format("The number of words beginning with %s are: %d", (char)i, characters[i]));
}
于 2013-03-30T18:33:33.187 回答