Loading

Pages

Wednesday, February 20, 2013

How To Keep The Order Of Elements In A Java Map

The normal HashMap does not guarantee the insertion order of entries. If maintaining the insertion order is important, use the LinkedHashMap instead.

Sample:
import java.util.HashMap;  
 import java.util.LinkedHashMap;  
 import java.util.Map;  
 public class LinkedHashMapTest {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           Mapmap=new HashMap();  
           map.put("ONE","1");  
           map.put("three","3");  
           map.put("FIVE","5");  
           map.put("seven","7");  
           System.out.println("Output from HashMap:");  
           for(Map.Entryentry:map.entrySet()){  
                System.out.println(entry.getKey()+":"+entry.getValue());  
           }  
           System.out.println("\nOutput from LinkedHashMap:");  
           MaporderedMap=new LinkedHashMap();  
           orderedMap.put("ONE","1");  
           orderedMap.put("three","3");  
           orderedMap.put("FIVE","5");  
           orderedMap.put("seven","7");  
           for(Map.Entryentry:orderedMap.entrySet()){  
                System.out.println(entry.getKey()+":"+entry.getValue());  
           }  
      }  
 } 
 
Output from HashMap:
seven:7
ONE:1
three:3
FIVE:5

Output from LinkedHashMap:
ONE:1
three:3
FIVE:5
seven:7 

No comments: