RSS Feed for This PostCurrent Article

Java: Ordered Map and Set

If you need an ordered Map or Set, meaning maintaining the original in your Map or Set in the order you insert or add them, then you should use LinkedHashMap or LinkedHashSet.

Some sample code below.

   1: import java.util.*;
   2:  
   3: public class TestClass {
   4:  
   5:     public static void main(String[] args) {
   6:         Map<String, String> unOrdereddMap = new HashMap<String, String>();
   7:         unOrdereddMap.put("1", "one");
   8:         unOrdereddMap.put("2", "two");
   9:         unOrdereddMap.put("3", "three");
  10:         for (String key : unOrdereddMap.keySet()) {
  11:             System.out.println(unOrdereddMap.get(key));
  12:         }
  13:  
  14:         Map<String, String> orderedMap = new LinkedHashMap<String, String>();
  15:         orderedMap.put("1", "one");
  16:         orderedMap.put("2", "two");
  17:         orderedMap.put("3", "three");
  18:         for (String key : orderedMap.keySet()) {
  19:             System.out.println(orderedMap.get(key));
  20:         }
  21:  
  22:  
  23:         Set<String> unOrderedSet = new HashSet<String>();
  24:         unOrderedSet.add("1");
  25:         unOrderedSet.add("2");
  26:         unOrderedSet.add("3");
  27:         for (String value : unOrderedSet)
  28:             System.out.println(value);
  29:  
  30:  
  31:         Set<String> orderedSet = new LinkedHashSet<String>();
  32:         orderedSet.add("1");
  33:         orderedSet.add("2");
  34:         orderedSet.add("3");
  35:         for (String value : orderedSet)
  36:             System.out.println(value);
  37:  
  38:  
  39:     }
  40:  
  41:  
  42: }

LinkedHashMap and LinkedHashSet iterator follow the insertion order whereas the HashMap and HashSet are not.

The output

   1: three
   2: two
   3: one
   4:  
   5: one
   6: two
   7: three
   8:  
   9: 3
  10: 2
  11: 1
  12:  
  13: 1
  14: 2
  15: 3


Trackback URL


RSS Feed for This PostPost a Comment

CAPTCHA Image
Refresh Image
*