1

I have made a program which will read in text from the user, and then display the letter frequencies of the user's text. I am experimenting with hashmaps and I am not sure how to display my results in alphabetical order.

I currently have:

Map<Character, Integer> map = new HashMap<Character, Integer>();    
for (int i = 0; i < user.length(); i++) {
  Integer count = map.get(user.charAt(i)); // if not in map
  if (count == null)
    map.put(user.charAt(i), 1);
  else
    map.put(user.charAt(i), count + 1);
}

As my code for storing the values, but when I print the result

System.out.println(map.entrySet());

I get [a=1, r=2, h=1, y=1]. (For printing "Harry")

Harry Jones
  • 73
  • 2
  • 3
  • 11

2 Answers2

2

What you're looking for is a collection that would implement the SortedMap interface. Try using TreeMap, which guarantees the natural ordering of its keys.

This question describes differences between various implementations of Map: Difference between HashMap, LinkedHashMap and TreeMap

Community
  • 1
  • 1
AtomHeartFather
  • 954
  • 17
  • 35
1

Use TreeMap instead of HashMap.

davide
  • 1,918
  • 2
  • 20
  • 30