你知道Java遍历Map集合的方法有哪些吗?下面的文章要给大家介绍的就是java遍历Map集合的四种方法,一起来具体的看下吧。
1、在for循环当中,使用entries实现Map的遍历。public static void main(String[] args)
{
Map map = new HashMap ();
map.put("Java入门教程", "http://c.biancheng.net/java/");
map.put("C语言入门教程", "http://c.biancheng.net/c/");
for (Map.Entry entry: map.entrySet())
{
String mapKey = entry.getKey();
String mapValue = entry.getValue();
System.out.println(mapKey + ":" + mapValue);
}
}
2、使用for-each循环遍历key或者values,一般适用于只需要Map中的key或者value时使用。Map map = new HashMap ();
map.put("Java入门教程", "http://c.biancheng.net/java/");
map.put("C语言入门教程", "http://c.biancheng.net/c/");
// 打印键集合
for (String key: map.keySet())
{
System.out.println(key);
}
// 打印值集合
for (String value: map.values())
{
System.out.println(value);
}
性能上比entrySet较好。
3、使用迭代器(Iterator)遍历。Map map = new HashMap ();
map.put("Java入门教程", "http://c.biancheng.net/java/");
map.put("C语言入门教程", "http://c.biancheng.net/c/");
Iterator > entries = map.entrySet()
.iterator();
while (entries.hasNext())
{
Entry entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + ":" + value);
}
4、通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作。for (String key: map.keySet())
{
String value = map.get(key);
System.out.println(key + ":" + value);
}
这四种方式你都了解了吗?更多和java Map集合相关jav基础内容,请继续通过奇Q工具网的java入门栏目来进行了解吧。
推荐阅读: