How to Iterate over the Items in Java’s Map (HashMap, Hash

  • 时间:2020-09-11 08:17:29
  • 分类:网络文摘
  • 阅读:126 次

Iterating over the items in the Java’s Map is very useful. The java.util.Map is a interface where you could have concrete implementations such as java.util.HashMap or java.util.TreeMap.

Iterate elements over java.util.HashMap

The java.util.HashMap is unordered. Thus if you iterate the elements in the hashmap, you’ll get unordered elements that are not exactly the same as they are inserted into the hashmap.

For example, let’s create a HashMap and put five key-value pairs into the hashmap.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.HashMap;
import java.util.Map;
 
public class Main {
    public static void main(String[] args) {
        Map<String, Integer> data = new HashMap<>();
        data.put("key1", 1);
        data.put("key2", 2);
        data.put("key3", 3);
        data.put("key4", 4);
        data.put("key5", 5);
        for (Map.Entry<String, Integer> entry: data.entrySet()) {
            System.out.println(entry.getKey() + " -- " + entry.getValue());
        }
    }
}
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> data = new HashMap<>();
        data.put("key1", 1);
        data.put("key2", 2);
        data.put("key3", 3);
        data.put("key4", 4);
        data.put("key5", 5);
        for (Map.Entry<String, Integer> entry: data.entrySet()) {
            System.out.println(entry.getKey() + " -- " + entry.getValue());
        }
    }
}

Iterating the elements in the hashmap can be achieved by looping over the hashmap.entrySet() – then key and value can be obtained via entry.getKey() and entry.getValue() methods.

One example output would be:

key1 -- 1
key2 -- 2
key5 -- 5
key3 -- 3
key4 -- 4

If you are looking for synchronised hashmap, you could also try java.util.Hashtable. Iterating over Hashtable can be done in the same syntax.

How to Iterate the elements in the Java’s TreeMap

Java’s TreeMap internally implements a Red-Black Tree. Therefore, if you iterate the TreeMap, you’ll get a sorted sequence based on the keys.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.TreeMap;
import java.util.Map;
 
public class Main {
    public static void main(String[] args) {
        Map<String, Integer> data = new TreeMap<>();
        data.put("key4", 4);
        data.put("key2", 2);
        data.put("key5", 5);
        data.put("key3", 3);
        data.put("key1", 1);
        for (Map.Entry<String, Integer> entry: data.entrySet()) {
            System.out.println(entry.getKey() + " -- " + entry.getValue());
        }
    }
}
import java.util.TreeMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> data = new TreeMap<>();
        data.put("key4", 4);
        data.put("key2", 2);
        data.put("key5", 5);
        data.put("key3", 3);
        data.put("key1", 1);
        for (Map.Entry<String, Integer> entry: data.entrySet()) {
            System.out.println(entry.getKey() + " -- " + entry.getValue());
        }
    }
}

The output will be sorted:

key1 -- 1
key2 -- 2
key3 -- 3
key4 -- 4
key5 -- 5

As listed above, the Map can be iterated via the same techniques as long as the hashmap implements the java.util.Map interface.

The entrySet returns the Set that is type of Entry:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    /**
     * Returns a {@link Set} view of the mappings contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own remove operation, or through the
     * setValue operation on a map entry returned by the
     * iterator) the results of the iteration are undefined.  The set
     * supports element removal, which removes the corresponding
     * mapping from the map, via the Iterator.remove,
     * Set.remove, removeAll, retainAll and
     * clear operations.  It does not support the
     * add or addAll operations.
     *
     * @return a set view of the mappings contained in this map
     */
    Set<Map.Entry<K, V>> entrySet();
    /**
     * Returns a {@link Set} view of the mappings contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own remove operation, or through the
     * setValue operation on a map entry returned by the
     * iterator) the results of the iteration are undefined.  The set
     * supports element removal, which removes the corresponding
     * mapping from the map, via the Iterator.remove,
     * Set.remove, removeAll, retainAll and
     * clear operations.  It does not support the
     * add or addAll operations.
     *
     * @return a set view of the mappings contained in this map
     */
    Set<Map.Entry<K, V>> entrySet();

And the Map.Entry is a interface that provides: getKey(), getValue() and etc methods.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
三类护耳食物可以延缓老年人听力下降  红枣养生知识:食用红枣需注意的问题  健康面点拒绝这些有毒的添加剂原料  火锅健康吃法:先素后荤 煮烫适度 少吃辣  柚子的保健功效以及食用柚子的禁忌  许多人已经走入了补充益生菌的误区  怎么吃核桃对男人的补肾效果最好  人体感冒时候应避免食用这些食物  感冒时多吃这些食物有助于感冒治愈  白糖在家庭厨房里烹调食物中的妙用 
评论列表
添加评论