How To Sort HashMap Keys In Java Without Using TreeMap?

preview_player
Показать описание
Most Frequently asked question in Interview.
How To Sort HashMap Keys In Java Without Using TreeMap?
Рекомендации по теме
Комментарии
Автор

If you are giving keys as Integers it will any way gives out put in sorted order (though HashMap doesnt store value in sorted order), so better example can be if HashMap contains two Strings like HashMap<String, String> hm . I did it from your program, so thanks a lot for this tutorial . Here is your program just removed some lines .

package
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SortHashMap {

private static void sortHashMap(Map<String, String> unsortedMap) {
List<String> list= new
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1) ;
}
});

System.out.println("Sorted HashMap in ascending order");
//as we are storing sorted keys of Map in the list we can get keys from list itself
for ( String keys : list)
{
System.out.println(keys +"..."+unsortedMap.get(keys) );
}
}

public static void main(String[] args) {
Map<String, String> unsortedMap = new HashMap<>();
unsortedMap.put("th", "three");
unsortedMap.put("fo", "four");
unsortedMap.put("on", "one");
unsortedMap.put("si", "six");

System.out.println("Before sorting : ");
for( String val : unsortedMap.values() )
{
System.out.println(val );
//Prints only value without any sorted order, as HashMap is used here (Hashing Technique)
}
sortHashMap(unsortedMap);
}
}

kuldeepsahoo
join shbcf.ru