how to sort Key in hashmap in java

Key Sorting of hashmap in java
SOURCE : HasMapSort.java


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 HasMapSort {

public static void main(String[] args) {

HashMap 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);

ArrayList> entries = new ArrayList<>(hmap.entrySet());

Collections.sort(entries,new Comparator>() {

@Override
public int compare(Entry o1, Entry o2) {

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

for(Map.Entry hm : entries){
System.out.println(hm);

}
}

}





INPUT

map = {Aandy=78, ndy=67, gahdhj=4, phdb=676, sandy=34, andy=94}



OUTPUT

gahdhj=4
sandy=34
ndy=67
Aandy=78
andy=94
phdb=676







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