Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,945 questions

51,887 answers

573 users

How to find the number of occurrences (frequency) of each word in a string in Java

1 Answer

0 votes
import java.util.TreeMap;
import java.util.Map;

public class MyClass {
    static Map<String, Integer> getOccurrences(String s) {
        Map<String, Integer> mp = new TreeMap<>();
 
        String arr[] = s.split(" ");
 
        for (int i = 0; i < arr.length; i++) {
            if (mp.containsKey(arr[i])) {
                mp.put(arr[i], mp.get(arr[i]) + 1);
            }
            else {
                mp.put(arr[i], 1);
            }
        }
        
        return mp;
    }
    public static void main(String args[]) {
        String s = "php c java c++ java python c# c c java java";
 
        Map<String, Integer> mp = getOccurrences(s);
        
        for (Map.Entry<String, Integer> entry: mp.entrySet()) {
            System.out.println(entry.getKey() + " - " + entry.getValue());
        }
    }
}




/*
run:

c - 3
c# - 1
c++ - 1
java - 4
php - 1
python - 1

*/

 



answered Jan 19, 2021 by avibootz
edited Jan 19, 2021 by avibootz
...