Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Printing out a Map in sorted order

// print out a Map in sorted order of its keys

   1  
   2      public static String dumpToString(Map<String, Object> map) {
   3          if (map == null) {
   4              return Constants.EMPTY_STRING;
   5          }
   6  
   7          StringBuffer strbuf = new StringBuffer();
   8  
   9          SortedMap<String, Object> sMap = new TreeMap<String, Object>(map);
  10          Set<Map.Entry<String, Object>> s = sMap.entrySet();
  11  
  12          for (Map.Entry<String, Object> elem : s) {
  13              String key = elem.getKey();
  14              Object value = elem.getValue();
  15              strbuf.append(key);
  16              strbuf.append("=");
  17              strbuf.append(value == null ? Constants.EMPTY_STRING : value);
  18              strbuf.append("\r\n");
  19          }
  20  
  21          return strbuf.toString();
  22      }

Recursively dump imbricated Map of Maps

// description of your code here

   1  
   2      public void dumpMapOfMap(Map map) {
   3          Set s = map.entrySet();
   4          Iterator sit = s.iterator();
   5          boolean isFirst = true;
   6  
   7          while (sit.hasNext()) {
   8              Map.Entry elem = (Map.Entry)sit.next();
   9              String key = (String)elem.getKey();
  10              Object value = elem.getValue();
  11  
  12              if (value instanceof String) {
  13                  // recursivity stop condition
  14                  System.out.print(key);
  15                  System.out.print(" : ");
  16                  System.out.println(value);
  17              } else {
  18                  if (!isFirst) {
  19                      System.out.println("");
  20                  } else {
  21                      isFirst = false;
  22                  }
  23                  System.out.println(key);
  24                  Map valueMap = (Map)elem.getValue();
  25                  dumpMapOfMap(valueMap);
  26              }
  27          }
  28      }
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS