Hashmap sorting
1. sort by key
For map sorting in Java, there is a Sort map, such as treemap. For this map, you can only sort by key first, and then sort by put and remove, performance may be compromised.
In this solution, hashmap is used for creation and addition. If you want to sort by key, you can pass this hashmap as a parameter to new treemap (hashmap). Then you can sort by key:
Treemap =NewTreemap (hashmap );
Treemap = new treemap (hashmap );
2. sort by value
Use hashmap, add comparator, and sort
Map <string, integer> keyfreqs =NewHashmap <string, integer> ();
Arraylist <entry <string, integer> L =NewArraylist <entry <string, integer> (keyfreqs. entryset ());
Collections. Sort (L,NewComparator <map. Entry <string, integer> (){
Public IntCompare (Map. Entry <string, integer> O1, map. Entry <string, integer> O2 ){
Return(O2.getvalue ()-o1.getvalue ());}});
For(Entry <string, integer> E: l ){
System. Out. println (E. getkey () + ":" + E. getvalue ());
}
Hashmap Traversal
In Java, hashmap is mainly used in two traversal methods. The Code is as follows:
First:
Hashmap = new hashmap ();
Iterator = hashmap. keyset (). iterator ();
While (iterator. hasnext ()){
Object value = hashmap. Get (iterator. Next ());
}
Second:
Hashmap = new hashmap ();
Iterator = hashmap. entryset (). iterator ();
While (iterator. hasnext ()){
Entry entry = (entry) iterator. Next ();
Object value = entry. getvalue ();
Object key = entry. getkey ();
}