Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Bonsai Boy of New York Bonsai Trees and Accessories

BlueHost Web Hosting

Liquid Web Managed Dedicated Server: RAID 1 SSD with 16GB of RAM minimum! 24/7 On-Site Heroic Support! Industry-Leading SLA!

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Liquid Web Cloud VPS Hosting

9,848 questions

13,460 answers

573 users

How to count the occurrence of each character in a string with Java

2 Answers

0 votes
import java.io.*; 
import java.util.*; 

public class MyClass { 
    static void charactersOccurrences(String s) { 
        HashMap<Character, Integer> hmap = new HashMap<Character, Integer>(); 
        char[] arr = s.toCharArray(); 

        for (char ch : arr) { 
            if (hmap.containsKey(ch)) { 
                hmap.put(ch, hmap.get(ch) + 1); 
            } 
            else { 
                hmap.put(ch, 1); 
            } 
        } 

        for (Map.Entry entry : hmap.entrySet()) { 
            System.out.println(entry.getKey() + " " + entry.getValue()); 
        } 
    }  
    public static void main(String args[]) {
        String s = "java programming";

        charactersOccurrences(s);
    }
}
 
 
/*
run:

  1
p 1
a 3
r 2
v 1
g 2
i 1
j 1
m 2
n 1
o 1

*/

 




answered Feb 7 by avibootz
edited Feb 7 by avibootz
0 votes
import java.io.*; 
import java.util.*; 

public class MyClass { 
    static HashMap charactersOccurrences(String s) { 
        HashMap<Character, Integer> hmap = new HashMap<Character, Integer>(); 
        char[] arr = s.toCharArray(); 

        for (char ch : arr) { 
            if (hmap.containsKey(ch)) { 
                hmap.put(ch, hmap.get(ch) + 1); 
            } 
            else { 
                hmap.put(ch, 1); 
            } 
        } 
        return hmap;
    }  
    public static void main(String args[]) {
        String s = "java programming";

        HashMap<Character, Integer> hmap = charactersOccurrences(s);
        
        for (Map.Entry entry : hmap.entrySet()) { 
            System.out.println(entry.getKey() + " " + entry.getValue()); 
        } 
    }
}
 
 
/*
run:

  1
p 1
a 3
r 2
v 1
g 2
i 1
j 1
m 2
n 1
o 1

*/

 




answered Feb 7 by avibootz
...