Map.Entry

Module java.base
Package java.util
Interface Map.Entry
<K,​V> All Known Implementing Classes: AbstractMap.SimpleEntry, AbstractMap.SimpleImmutableEntry
Enclosing
interface: Map<K,​V>
public static interface Map.Entry<K,​V> A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.
Since:
1.2

See Also: Map.entrySet()

 

示例:

import java.util.Map;

public class IteratorDemo {
    public static void main(String[] args) {
        Map.Entry<String, Integer> entry = Map.entry("one", 1);
        System.out.println("Key=" + entry.getKey());
        System.out.println("Value=" + entry.getValue());
        System.out.println(entry);
        System.out.println(entry.getClass().getName());
    }
}

运行结果:

Key=one
Value=1
one=1
java.util.KeyValueHolder

 

经过分析可以发现:如果想要使用Iterator实现Map集合的输出,则必须按照如下步骤处理:

  • 利用Map接口中提供的entrySet()方法将Map集合转为Set集合;
  • 利用Set接口中的iterator()方法将Set集合转为Iterator接口实例;
  • 利用Iterator进行迭代输出,获取每一组的Map.Entry对象,随后通过getKey()和getValue()方法获取数据。

示例:利用Iterator输出Map集合

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class IteratorDemo {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);
        Set<Map.Entry<String, Integer>> set = map.entrySet();//将Map集合转为Set集合
        Iterator<Map.Entry<String, Integer>> iter = set.iterator();//将Set集合转为Iterator接口实例
        while (iter.hasNext()) {
            Map.Entry<String, Integer> me = iter.next();//获取每一组的Map.Entry对象
            System.out.println(me.getKey() + "=" + me.getValue());
        }
    }
}

运行结果:

one=1
two=2
three=3

 

  虽然Map集合本身支持迭代输出,但是如果从实际的开发来讲,Map集合最主要的用法在于实现数据的key查找操作,另外需要提醒的是,如果现在不使用Iterator而使用forEach愈发输出,也需要将Map集合转为Set集合。

示例:使用forEach输出Map集合

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class IteratorDemo {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);
        Set<Map.Entry<String, Integer>> set = map.entrySet();//将Map集合转为Set集合
        for(Map.Entry<String, Integer> entry: set) {
            System.out.println(entry.getKey()+"="+entry.getValue());
        }
    }
}

运行结果:

one=1
two=2
three=3

 

点赞