您的位置:首页 > 编程语言 > Java开发

Java中遍历Map的几种方式

2017-12-06 11:20 507 查看
1.Map中提供给了一些常用方法,如keySet()、value()、entrySet()用于取出元素

keySet()方法:返回此映射中所包含的键的 set 视图(集合)

public Set<K> keySet()


value()方法:返回此映射所包含的值的 collection 视图

public Collection<V> values()


entrySet()方法:返回此映射所包含的映射关系的 collection 视图(这边有点疑问:因为事实上返回的是Set),在返回的集合中,每个元素都是一个Map.Entry

public Set<Map.Entry<K,V>> entrySet()


一个具体的例子:

class HelloWorld
{
public static void main(String[] args)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("1","one");
map.put("2","two");
map.put("3", "tree");
map.put("4", "four");
//使用keySet方法,取出所有的键组成Set集合
System.out.println(map.keySet());
//使用values方法,取出所有的值组成的Collection
System.out.println(map.values());
//entrySet()方法,取出 所有的键-值组成Set集合
System.out.println(map.entrySet());
}
}


程序运行结果打印如下,可以看到分别返回所有的键、所有的值和所有的键-值的组合:

[3, 2, 1, 4]
[tree, two, one, four]
[3=tree, 2=two, 1=one, 4=four]


2.如何将Map中的键,值取出,有三种常见的方法:
第一种方法:是先通过keySet()方法取出键,再通过迭代分别取出对应的值

class HelloWorld
{
public static void main(String[] args)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("01", "zhangsan");
map.put("02", "lisi");
map.put("03", "wangwu");
Set<String> set = map.keySet();			//得到由键组成的Set集合
Iterator<String> it = set.iterator();
while(it.hasNext())
{
String key = it.next();
String value = map.get(key);		//通过get方法,获取键对应的值
System.out.println(key+" "+value);	//将键和值都打印出来
}
}
}


第二种方法:

class HelloWorld
{
public static void main(String[] args)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("01", "zhangsan");
map.put("02", "lisi");
map.put("03", "wangwu");

Set<Map.Entry<String,String>> entry = map.entrySet();		//得到包含映射关系的collecton视图
Iterator<Map.Entry<String, String>> it = entry.iterator();
while(it.hasNext())
{
Map.Entry<String,String> me = it.next();
System.out.println(me.getKey()+" "+me.getValue());		//通过getKey()得到键
}									//通过getValue()得到值
}
}

说明:在返回的Set集合中,每个元素都是一个 Map.Entry,再通过iteraor来访问该集合,得到每个Map.Entry元素,最后通过getKey()和getValue()方法得到键和值

第三种方法(这个方法只能取出值):

class HelloWorld
{
public static void main(String[] args)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("01", "zhangsan");
map.put("02", "lisi");
map.put("03", "wangwu");

Collection<String> collection = map.values(); //通过values方法得到包含所有值Collection视图
Iterator<String> it = collection.iterator();
while(it.hasNext())
{
String name = it.next();
System.out.println(name);				  //打印出所有的值
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: