0

I jave a map containing String as Key and float as value in java. How to sort them efficiently. I tried to use comparator , but stuck badly.

Map<String,Float> map = new HashMap<String,Float>();
map.put("A",(float)3.24);
map.put("A",(float)3.14);

Sorry my problem is to sort based on fractional part of the value ie .24 and .14

How to sort the above in java.

Abhishek Choudhary
  • 8,255
  • 19
  • 69
  • 128

3 Answers3

2

If you want them ordered by key, use a Treemap instead of a Hashmap.

Javadoc for Treemap

BillRobertson42
  • 12,602
  • 4
  • 40
  • 57
2

Use TreeMap instead of HashMap. TreeMap will automatically sorted.

Note: HashMap, TreeMap wont allow duplicate keys.

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

You can use a TreeMap that implement SortedMap. check this link http://docs.oracle.com/javase/tutorial/collections/interfaces/sorted-map.html

user2084446
  • 119
  • 2
  • 2
  • 8