fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. String str = "hello world";
  13.  
  14. Map<Character, Integer> lettersCount = new HashMap<>();
  15.  
  16. for (int i=0; i <str.length(); i++) {
  17. Character current = str.charAt(i);
  18. if (Character.isLetter(current)) {
  19. Integer previousCount = lettersCount.get(current);
  20. if (previousCount != null) {
  21. lettersCount.put(current, previousCount + 1);
  22. } else {
  23. lettersCount.put(current, 1);
  24. }
  25. }
  26. }
  27. List<Map.Entry<Character, Integer>> list = new LinkedList<Map.Entry<Character, Integer>>( lettersCount.entrySet() );
  28. Collections.sort( list, new Comparator<Map.Entry<Character, Integer>>()
  29. {
  30. public int compare( Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2 )
  31. {
  32. return (o2.getValue()).compareTo( o1.getValue() );
  33. }
  34. } );
  35. for (Map.Entry<Character, Integer> entry : list) {
  36. System.out.println(entry.getKey() + " : " + entry.getValue());
  37. }
  38. }
  39. }
Success #stdin #stdout 0.1s 320512KB
stdin
Standard input is empty
stdout
l : 3
o : 2
r : 1
d : 1
e : 1
w : 1
h : 1