Java Application Notes: HashMap

Collect common operations in HashMap, including iteration, sorting.

1. Nested HashMap declaration

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

// Note: a compile error
Map<String, Map<String, String>> map = new HashMap<String, HashMap<String,String>>();

2. Key existence

Check if a given key exists in HashMap by[1]:

/*** Case 1: a null value is not stored ***/
Foo value = map.get(key);
if (value != null) {
    ...
} else {
    // No such key
}

/*** Case 2: store a null value ***/
Foo value = map.get(key);
if (value != null) {
    ...
} else {
    // Key might be present...
    if (map.containsKey(key)) {
       // there's a key but the value is null
    } else {
       // Definitely no such key
    }
}

3. Iteration

3.1 Iterate over key and/or value

(1) Iterate through key

Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
    // ...
}

(2) Iterate through value

Map<String, String> map = new HashMap<String, String>();
for (String value : map.values()) {
    // ...
}

(3) Iterate through key and value

Map<String, String> map = new HashMap<String, String>();
for (Map.Entry<String, String> entry : map.entrySet())
{
    String key = entry.getKey();
    String value = entry.getValue();
}

3.2 Remove items in mid-iteration

Map<String, String> map = new HashMap<String, String>();
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    String key = pair.getKey();
    String value = pair.getValue();

    it.remove(); // avoids a ConcurrentModificationException
}

4. Sort

4.1 Sort by key

Used sorted TreeMap,

Map<String, String> hashmap = new HashMap<String, String>();
Map<String, String> treemap = new TreeMap<String, String>(hashmap); //automatically, natural String ordering

4.2 Sort by value[3]

static Map sortByValue(Map map) {
     List list = new LinkedList(map.entrySet());
     Collections.sort(list, new Comparator() {
          public int compare(Object o1, Object o2) {
               return ((Comparable) ((Map.Entry) (o1)).getValue())
              .compareTo(((Map.Entry) (o2)).getValue());
          }
     });

    Map result = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry)it.next();
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
} 

References:
[1]StackOverflow: Key existence check in HashMap
[2]StackOverflow: Iterate through a HashMap [duplicate]
[3]StackOverflow: How to sort a Map<Key, Value> on the values in Java?

发表评论

电子邮件地址不会被公开。 必填项已用*标注