Harry Jones
Harry Jones

Reputation: 73

How to sort HashMap entries in alphabetic order?

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")

Upvotes: 1

Views: 797

Answers (2)

AtomHeartFather
AtomHeartFather

Reputation: 957

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

Upvotes: 2

davide
davide

Reputation: 1948

Use TreeMap instead of HashMap.

Upvotes: 1

Related Questions