计算文本文件使用映射中的出现次数

时间:2010-12-06 03:55:23

标签: java collections

下面的代码将计算每个角色的出现次数。如果我在文本文件输出中有abc将是1 b 1 c 1.我在许多网站中读到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);
        }
        }
    }

2 个答案:

答案 0 :(得分:2)

快速伪代码。基本上,这里的技巧是将字符保存为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));
}

答案 1 :(得分:0)

FileInputStream file = new FileInputStream(“”);             DataInputStream dis = new DataInputStream(file);             BufferedReader br = new BufferedReader(new InputStreamReader(dis));

        String temp="";
        Map<String,Integer> charCounter = new HashMap<String,Integer>();
      while ((temp=br.readLine()) != null)
      {
         String[] spliter= temp.split("");
         for(String temp1:spliter)
         if(charCounter.containsKey(temp1)){
               charCounter.put(temp1,charCounter.get(temp1)+1);
        }else{
              charCounter.put(temp1,1);
        }


      }


            System.out.println(charCounter);

构建逻辑coolbean给了hav写它..希望这会有所帮助......我已经测试了这个..