Pacific-Design.com

    
Home Index

1. Algorithms

2. 02 Hash Map Sorted

Algorithms / 02 Hash Map Sorted /

Hash Map Sorted

import java.util.*;

class SortMapKey {

    static Map<String, Integer> map = new HashMap<>();

    public static void main(String args[])
    {
        map.put("Los Angeles", 98);
        map.put("Agoura Hills", 12);
        map.put("Woodland Hills", 35);
        map.put("Calabasas", 46);
        map.put("Thousand Oaks", 27);
 
        sortByKey();
    }

    public static void sortByKey()
    {
        // TreeMap to store values of HashMap
        TreeMap<String, Integer> treeMap = new TreeMap<>();

        // Copy all data from hashMap into TreeMap
        treeMap.putAll(map);

        // Display the TreeMap which is naturally treeMap
        for (Map.Entry<String, Integer> entry : treeMap.entrySet()) 
            System.out.println("Key = "     + entry.getKey() + 
                               ", Value = " + entry.getValue());        
    }

}