14

The below code is to count the occurence of each character and it should print the count. But with the code I have tried I get only a 1 I don't know the changes I should make.

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

class Count_CharMap {
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();
        int count = 0;
        char ch = char_array[count];
        Map<Character,Integer> charCounter=new HashMap<Character,Integer>();
        for(int i=0;i<str.length();i++)
        {
            if(charCounter.containsKey(char_array[i]))
            {
                charCounter.put(ch, charCounter.get(ch)+1);
            } 
            else
            {
                charCounter.put(ch, 1);
            }
       }

       for(Character key:charCounter.keySet())
       {
           System.out.println(key+""+charCounter.get(key));
       }
    } 
    catch(IOException e1){
        System.out.println(e1);
    }
    }
}

Actual output should be like If i have abcdabc in my trial.txt it should print a 2 b 2c 2 d 1.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sumithra
  • 6,587
  • 19
  • 51
  • 50

11 Answers11

14

You're leaving char ch set as the same character through each execution of the loop.

It should be:

ch = char_array[i]; 
if(charCounter.containsKey(ch)){
     charCounter.put(ch, charCounter.get(ch)+1);
}
else
{
    charCounter.put(ch, 1);
}

Inside the for loop.

Paul
  • 2,729
  • 20
  • 26
  • hay thanks a lot. Silly i m :-) The code perfectly prints all the characters and occurences. I want to print them in alphabetical order. How to do that? – Sumithra Dec 06 '10 at 06:09
  • 2
    Use a treemap instead of a hashmap and it should do it. If not you'll have to sort it using a comparator, google it. http://download.oracle.com/javase/1.4.2/docs/api/java/util/TreeMap.html – Paul Dec 06 '10 at 06:10
8

Java 8 streams:

Map<String, Long> map = 
    Arrays.stream(string.split("")).
    collect(Collectors.groupingBy(c -> c, Collectors.counting()));

Guava HashMultiset:

Multiset<Character> set = HashMultiset.create(Chars.asList("bbc".toCharArray()));
assertEquals(2, set.count('b'));
Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
4

Hai All The below code is to count the occurrence of each character and it should print the count. may be helps you..Thanks for seeing

package com.corejava;

import java.util.Map;
import java.util.TreeMap;

public class Test {
    public static void main(String[] args) {

        String str = "ramakoteswararao";

        char[] char_array = str.toCharArray();

        System.out.println("The Given String is : " + str);

    Map<Character, Integer> charCounter = new TreeMap<Character, Integer>();

        for (char i : char_array) {

    charCounter.put(i,charCounter.get(i) == null ? 1 : charCounter.get(i) + 1);

        }

    for (Character key : charCounter.keySet()) {
  System.out.println("occurrence of '" + key + "' is  "+ charCounter.get(key));
        }

    }

}
  • Hi, welcome to SO. When you post a solution in code, it may be helpful to include a short summary of the line of thought. – Marc Claesen May 20 '13 at 13:29
1
import java.util.HashMap;
import java.util.Map;
...
Map<String, Integer> freq = new HashMap<String, Integer>();
...
int count = freq.containsKey(word) ? freq.get(word) : 0;
freq.put(word, count + 1);
atiruz
  • 2,782
  • 27
  • 36
0

inside the for loop

ch = char_array[i];
charCounter.put(charCounter.contains(ch)?charCounter.get(ch)+1:1);

shyam karwa
  • 213
  • 1
  • 3
  • 8
0
import java.util.TreeMap;

public class OccuranceDemo {
    public static void main(String[] args) {
        TreeMap<String , Integer> mp=new TreeMap();
        String s="rain rain go away";
        String[] arr = s.split(" ");
        int length=arr.length;
        for(int i=0;i<length;i++)
       {
         String h = arr[i];
        mp.put(h, mp.get(h)==null?1:mp.get(h)+1);
    }
    System.out.println(mp.get("go"));
  }
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
  • If we need we get any other key in the above example we have taken go – Teju J Gowda Jun 12 '17 at 12:23
  • Hi, welcome to SO. A good first try, but your answer doesn't actually meet a number of requirements: (1) It counts the words, not the characters (2) It does not print the words and the counts at the end - doesn't work for arbitrary strings (3) It does not Hashmap, as asked (4) It does not actually fix the asker's code, but offers another solution. Please read the question carefully in the future before asking. See this guide: https://stackoverflow.com/help/how-to-answer – kenny_k Jun 12 '17 at 12:45
0
    String str=new String("aabbbcddddee");
    char[] ch=str.toCharArray();
    HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
    for(char ch1:ch)
    {

        if(hm.containsKey(ch1))
        {
            hm.put(ch1,hm.get(ch1)+1);
        }
        else
        {
            hm.put(ch1,1);
        }
    }

    Set s1=hm.entrySet();
    Iterator itr=s1.iterator();

    while(itr.hasNext())
    {
        Map.Entry m1=(Map.Entry)itr.next();
        System.out.println(m1);
    }
0
import java.util.*;

public class Test {
    public static void main(String[] args) {

        String str = "STACKOVERFLOW";

        char[] char_array = str.toCharArray();

        System.out.println("The Given String is : " + str);

    Map<Character, Integer> charCounter = new TreeMap<Character, Integer>();

        for (char i : char_array) {

    charCounter.put(i,charCounter.get(i) == null ? 1 : charCounter.get(i) + 1);

        }

    for (Character key : charCounter.keySet()) {
  System.out.println("occurrence of '" + key + "' is  "+ charCounter.get(key));
        }

    }

}
Ayo K
  • 1,719
  • 2
  • 22
  • 34
0

public void mapPractices() {

    Map<Character, Integer> map = new HashMap<>();
    String dataString = "!@#$%^&*()__)(*&^%$#@!@#$%^&*(*&^%$#@!@#$%^&*()(*&^%$#@!@#$%^&*()(*&^%$#@!@#$%^&*()(*&^%$#";
    for (int i = 0; i < dataString.length(); i++) {

        char charAt = dataString.charAt(i);

        if (map.containsKey(charAt)) {
            int val = map.get(charAt);
            map.put(charAt, val+1);

        } else {

            map.put(charAt, +1);
        }

    }
    System.out.println("Characters ant the string=" + map);

}
0

a lambda one-liner
After the bug in the old-school-solution is fixed, here is an alternative solution in lambda that does the same thing:

Map<Character,Long> counts =
"an example string to work with".codePoints().boxed().collect(
    groupingBy( t -> (char)(int)t, counting() ) );

gets: { =5, a=2, e=2, g=1, h=1, i=2, k=1, l=1, m=1, n=2, o=2, p=1, r=2, s=1, t=3, w=2, x=1}
You can get the number of a specific character eg. 't' by:
counts.get( 't' )

(I also write a lambda solution out of morbid curiosity to find out how slow my solution is, preferably from the guy with the 10-line solution.)

Kaplan
  • 2,572
  • 13
  • 14
0

Paul's answer contains exact fix, but instead of lengthy if-else checks, you may use getOrDefault method available since Java 8 to achieve the same results:

Map<Character, Integer> charCounter = new HashMap<>();
for (char c : str.toCharArray()) {
  charCounter.put(c, charCounter.getOrDefault(c, 0) + 1);
}

In this code snippet, we iterate over each character in the input string and update the count of that character in the map. If the character is not already present in the map, it is added with a default value of 0 using getOrDefault.

Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90