下面的代码将计算每个字符的出现次数。如果我在文本文件中有abc,输出将是1 b 1 c1。我在许多站点中读到,for循环将花费大量时间,最好使用哈希映射来实现。谁能帮助我如何转换实现哈希图的程序?

 import java.io.*;

    class Count_Char {
    public static void main(String[] args) {
        try
        {
    FileInputStream file = new FileInputStream("D:\\trial.txt");
    DataInputStream dis = new DataInputStream(file);
    BufferedReader br = new BufferedReader(new InputStreamReader(dis));
    String Contents="";
    String str="";
    while ((Contents = br.readLine()) != null) {
    str+=Contents;
    }
    char[]char_array =str.toCharArray();
    for(int count =0;count<char_array.length;count++){
    char ch= char_array[count];
    int counter=0;
    for ( int i=0; i<char_array.length; i++){
    if (ch==char_array[i])
    counter++;
    }
    boolean flag=false;
    int j=count-1;
    while(j>=0)
        {

        if(ch==char_array[j])
            flag=true;
            j--;
        }
    if(!flag){
    System.out.println(ch+" "+counter);
    }
    }
        }catch(IOException e1){
            System.out.println(e1);
        }
        }
    }

最佳答案

快速伪代码。基本上,这里的技巧是将字符保存为Map中的键,而值则是该字符(键/值对)的出现次数。

 //declare a map to hold your characters and their counters
 Map<String,Integer> charCounter = new HashMap<String,Integer>();
 //the following if else logic goes when you are looping through your tokens
    if(charCounter.containsKey(<your character>)){
           charCounter.put(<your character>,charCounter.get(<your character>)+1);
    }else{
          charCounter.put(<your character>,1);
    }

遍历完成后,可以用这种方式打印地图。
for(String key : charCounter.keySet()) {
            System.out.println(key+" "+charCounter.get(key));
}

10-07 12:38