Map.Entry用法示例

一般在HashMap中可以通过key值得到value值,以key作为检索项。Map.Entry<K,V>可以作为条目的检索项。HashMap中有entrySet()方法,返回值是Set<Map.Entry<K,V>>,对于返回的条目集合,可使用迭代器访问每个条目的Key和Value值。Map.Entry中的主要方法:1、getKey() ,返回值是K;2、getValue(),返回值是V;3、setValue(V value),返回值是V,该方法用指定的值替换与此项对应的值。


用法举例如下,用迭代器遍历Map.Entry集合中的条目,并作相应处理:

		Map<String,String> map=new HashMap();
		map.put("sj","girl");
		map.put("lql", "girl");
		
		Iterator it=map.entrySet().iterator();
		while(it.hasNext())
		{
			Map.Entry<String,String> entry= (Map.Entry<String,String>)it.next();
			System.out.println("Before changing......");
			System.out.println(entry.getKey());
			System.out.println(entry.getValue());
			entry.setValue("lalala");
			System.out.println("After changing......");
			System.out.println(entry.getKey());
			System.out.println(entry.getValue());
			System.out.println("Ending......
");
		}
		

输出结果:
Before changing......
lql
girl
After changing......
lql
lalala
Ending......

Before changing......
sj
girl
After changing......
sj
lalala
Ending......


原文地址:https://www.cnblogs.com/eva_sj/p/3971165.html