2018-04-19

Write a program to count each unique words in a given string.




  1. public class WordCountByMapAlgoritham {

  2. public static void main(String[] args) {
  3. String s = "this is java code. this java code is highly recommended for java developer !!";
  4. String a[] = s.split(" ");
  5. Map<String, Integer> map = new HashMap<String, Integer>();

  6. for (String word : a) {
  7. if (map.get(word) != null) {
  8. map.put(word, map.get(word) + 1);
  9. } else
  10. map.put(word, 1);
  11. }
  12. System.out.println(map);
  13. }
  14. }

Output: 
{!!=1, java=3, code=1, code.=1, this=2, for=1, is=2, developer=1, highly=1, recommended=1}

No comments:

Post a Comment