Showing posts with label hashmap. Show all posts
Showing posts with label hashmap. Show all posts

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.getKey().compareTo(o2.getKey());
}
});

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

}
}

}





INPUT

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



OUTPUT

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







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+