Count the number of occurrences from a text file card

The code below will list the occurrences of each character. If I have abc in the output of a text file, it will be 1 b 1 c 1. I read on many sites that the cycle will take a lot of time, and it is better to implement the same with a hash map. Can any of you help me how to convert this program to a hash map implementation?

 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);
        }
        }
    }
+3
source share
2 answers

Fast pseudo code. Basically the trick is that you save the characters as keys on the map, and the value is the occurrence counter for that character (key / value pair).

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

After you finish moving, you can print the map this way.

for(String key : charCounter.keySet()) {
            System.out.println(key+" "+charCounter.get(key));
}
+2

FileInputStream file = new FileInputStream ("");           DataInputStream dis = new DataInputStream ();           BufferedReader br = BufferedReader ( 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 writtn it.. , ... .

0

Source: https://habr.com/ru/post/1778664/


All Articles