获得单词频率的更有效方法

hat*_*ack 1 java optimization

我想通过单词的开头计算ArrayList中每个单词的频率.例如[cat,cog,mouse]意味着有两个单词以c开头,一个单词以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);

}
Run Code Online (Sandbox Code Playgroud)

Ste*_*eph 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());
  }
Run Code Online (Sandbox Code Playgroud)

或使用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());
  }
Run Code Online (Sandbox Code Playgroud)

最佳实践

永远不要list.get(i),for(element : list)改为使用.并且永远不要ArrayList在签名中使用界面,List以便您可以更改实现.

  • deezy:为什么强制调用代码使用特定的列表实现?如果它出于某种原因使用LinkedList怎么办?使用ArrayList,您可以强制代码在调用之前进行转换... (2认同)