How to Sort HashMap based on Values


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class HasMpSort {

public static void main(String[] args) {

HashMap<String, Integer> hmap = new HashMap<>();

hmap.put("sandy",34);
hmap.put("andy",94);
hmap.put("Aandy",78);
hmap.put("ndy",67);
hmap.put("gahdhj",4);
hmap.put("phdb",676);
System.out.println(hmap);
ArrayList<Map.Entry<String, Integer>> entries = new ArrayList<>(hmap.entrySet());

Collections.sort(entries,new Comparator<Map.Entry<String, Integer>>() {

@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {

return o1.getValue().compareTo(o2.getValue());
}
});

for(Map.Entry<String, Integer> hm : entries){
System.out.println(hm);

}
}

}

 


Sandeep Kumar D

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.
- Sandeep Kumar D

Follow Me @Google+
SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment