-1

I want to sort this HashMap:

HashMap<Integer,Integer> hp=new HashMap<Integer,Integer>();

TreeMap<Integer,Integer> stm = new TreeMap<Integer,Integer>();
stm.putAll(hp);

In value reverse sorting.

If the values ​​are the same, I will use key as the next condition. Value is reverse but key is not.

Azeem
  • 7,094
  • 4
  • 19
  • 32
Visa De
  • 21
  • 3

2 Answers2

0

We can implement the sort of HashMap by referring to TreeMap's value sort. I tried to write a sample to share with you.

public class HashMapTest {
public static void main(String[] args) {
    Map<String, String> map = new HashMap<String, String>();
    map.put("c", "ccccc");
    map.put("a", "aaaaa");
    map.put("b", "bbbbb");
    map.put("d", "ddddd");

    List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
    Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
        //Ascending order
        public int compare(Entry<String, String> o1,
                Entry<String, String> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }

    });

    for(Map.Entry<String,String> mapping:list){ 
           System.out.println(mapping.getKey()+":"+mapping.getValue()); 
      } 
 }

the resule is

a:aaaaa

b:bbbbb

c:ccccc

d:ddddd

Jay Gong
  • 20,598
  • 2
  • 15
  • 22
0

Why don't you get the entrySet from the map and try sorting it by using creating a comparator according to your need. When it's sorted just create a new instance of map and iterate the sorted set into the map. Its a little costly but does what you need.

If you find any problems implementing this. Tell me I will give you the code. :)

Ashish Lohia
  • 259
  • 1
  • 11