喜欢用Java写程序的朋友都知道,我们常用的一种数据结构map中存储的是键值对,我们一般存储的方式是:

map.put(key, value);

而提取相应键的值用的方法是:

map.get(key);

      确实,这些就是map的基本方法,可是,如果我想查看map中所有的元素怎么办?也就是想遍历其中的每个元素。

      下面,我就介绍三种方法遍历map:

说明:我在map中存储的值是CSDN一博主的QQ签名,当我遍历的时候你会看到。


1.map不是集合,所以,map并不存在迭代器,但是,map中的一个方法可以使得map中的键成为一个集合,那么我们就可以利用集合的迭代器进行遍历,方法如下所示:

Set<Integer> s = (Set<Integer>)map.keySet();
        Iterator<Integer> it = s.iterator();
        int Key;
        String value;
        while(it.hasNext()) {
            Key = it.next();
            value = (String)map.get(Key);
            System.out.println(Key+":\t"+value);
        }  

2.map提供了另一个方法--entryset,使得我们可以获得map中存储的“键值对”集合,我们可以对键值对集合进行操作,进行遍历,方法如下所示:

Set<Entry<Integer, String>> s = map.entrySet();
        Iterator<Map.Entry<Integer, String>> it = s.iterator();
        Map.Entry<Integer, String> entry;
        int Key;
        String value;
        while(it.hasNext()) {
            entry = it.next();
            Key = entry.getKey();
            value = entry.getValue();
            System.out.println(Key+":\t"+value);
        }  

3.其实这种方法和第二种方法是一样的,只是我们用了不同的形式实现而已,这里不多说,方法如下:

for(Map.Entry<Integer, String> entry : map.entrySet()){
			System.out.println(entry.getKey() + ":\t" + entry.getValue());
		}

下面给出完整的测试代码以及运行后的结果:

package com.brucezhang.test;

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

public class MapItTest {

	private static Map<Integer, String> my_map = new HashMap<Integer, String>();

	private static String[] my_value = {"I love three things", "The sun for the day", "The moon for the night", "The you forever"};

	/**
	 * @param args
	 * Author:DLUTBruceZhang
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//给 map 赋初值
		for (int i = 0; i < my_value.length; i++) {
			my_map.put(i, my_value[i]);
		}

		//使用第一种方法进行遍历
		theFirstItFun(my_map);
		System.out.println("----------------------------------------");

		//使用第二种方法进行遍历
		theSecondItFun(my_map);
		System.out.println("----------------------------------------");

		//使用第三种方法进行遍历
		theThirdItFun(my_map);
	}

	public static void theFirstItFun(Map<Integer, String> map) {

		Set<Integer> s = (Set<Integer>)map.keySet();
        Iterator<Integer> it = s.iterator();
        int Key;
        String value;
        while(it.hasNext()) {
            Key = it.next();
            value = (String)map.get(Key);
            System.out.println(Key+":\t"+value);
        }
	}

	public static void theSecondItFun(Map<Integer, String> map){

		Set<Entry<Integer, String>> s = map.entrySet();
        Iterator<Map.Entry<Integer, String>> it = s.iterator();
        Map.Entry<Integer, String> entry;
        int Key;
        String value;
        while(it.hasNext()) {
            entry = it.next();
            Key = entry.getKey();
            value = entry.getValue();
            System.out.println(Key+":\t"+value);
        }
	}

	public static void theThirdItFun(Map<Integer, String> map){

		for(Map.Entry<Integer, String> entry : map.entrySet()){
			System.out.println(entry.getKey() + ":\t" + entry.getValue());
		}
	}

}


运行结果如下:

0:	I love three things
1:	The sun for the day
2:	The moon for the night
3:	The you forever
----------------------------------------
0:	I love three things
1:	The sun for the day
2:	The moon for the night
3:	The you forever
----------------------------------------
0:	I love three things
1:	The sun for the day
2:	The moon for the night
3:	The you forever

java中遍历map的几种方法介绍的更多相关文章

  1. Java中遍历map的四种方法 - 转载

    在Java中如何遍历Map对象 How to Iterate Over a Map in Java 在java中遍历Map有不少的方法.我们看一下最常用的方法及其优缺点. 既然java中的所有map都 ...

  2. Java中遍历Map的几种方法

      转自: http://blog.csdn.net/wzb56/article/details/7864911 方法分为两类: 一类是基于map的Entry:map.entrySet(); 一类是基 ...

  3. 谈谈java中遍历Map的几种方法

    java中的map遍历有多种方法,从最早的Iterator,到java5支持的foreach,再到java8 Lambda,让我们一起来看下具体的用法以及各自的优缺点 先初始化一个map public ...

  4. java 中遍历Map的几种方法

    方法分为两类: 一类是基于map的Entry:map.entrySet(); 一类是基于map的key:map.keySet() 而每一类都有两种遍历方式: a.利用迭代器 iterator: b.利 ...

  5. java中遍历map对象的多种方法

    在Java中如何遍历Map对象   How to Iterate Over a Map in Java 在java中遍历Map有不少的方法.我们看一下最常用的方法及其优缺点. 既然java中的所有ma ...

  6. Java原来如此-遍历Map的三种方法

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

  7. Java中遍历Map的四种方式

    Demo如下 Map<String, String> map = new HashMap<>(); map.put("key1","data1&q ...

  8. java中遍历map的两种方式

    1.先将map对象转成set,然后再转为迭代器 Iterator iterator = map.entrySet().iterator(); while(iterator.hasNext()){ En ...

  9. java中遍历MAP,嵌套map的几种方法

    java中遍历MAP的几种方法 Map<String,String> map=new HashMap<String,String>();    map.put("us ...

随机推荐

  1. bzoj2243[SDOI2011]染色 树链剖分+线段树

    2243: [SDOI2011]染色 Time Limit: 20 Sec  Memory Limit: 512 MBSubmit: 9012  Solved: 3375[Submit][Status ...

  2. [bzoj4813][Cqoi2017]小Q的棋盘

    来自FallDream的博客,未经允许,请勿转载,谢谢. 小Q正在设计一种棋类游戏.在小Q设计的游戏中,棋子可以放在棋盘上的格点中.某些格点之间有连线,棋子只能在有连线的格点之间移动.整个棋盘上共有V ...

  3. JavaBean实现用户登陆

    本文简单讲述使用javabean实现用户登录,包括用户登录,注册和退出等. 系统结构图 2.数据库表 create table P_USER ( id       VARCHAR2(50) not n ...

  4. Linux学习之CentOS(五)--CentOS下VMware-Tools安装

    已经进入到了Linux学习之CentOS的第六篇随笔了,所以这里就介绍一下VMware-Tools的安装. VMware-Tools的安装 VMware-Tools 主要的功能就是让用户在虚拟机和真实 ...

  5. Architecture : Describable Command and Identifiable Data

    Architecture : Describable Command and Identifiable Data Description Terms Command A command is a fu ...

  6. Socket.io应用之联网拖拽游戏

    服务器端代码: const express=require('express'); const http=require('http'); const sio=require('socket.io') ...

  7. Tomcat 报错的解决方法:The APR based Apache Tomcat Native library which allows optimal

    下载 http://tomcat.heanet.ie/native/1.1.12/binaries/win32/tcnative-1.dll将这个文件复制到C:\WINDOWS\system32\,. ...

  8. NOIP2017D2T3 列队—Treap

    NOIP2017列队 Description Sylvia 是一个热爱学习的女孩子.  前段时间,Sylvia 参加了学校的军训.众所周知,军训的时候需要站方阵. Sylvia所在的方阵中有n × m ...

  9. Node.js 模块系统

    为了让Node.js的文件可以相互调用,Node.js提供了一个简单的模块系统. 模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的.换言之,一个 Node.js 文件就是一个模块, ...

  10. Xcode编译错误__NSCFConstantString

    __NSCFConstantString:主要错误就是数据类型造成的,然后就是检查哪个地方造成的数据类型调用错误 错误一:'-[__NSCFConstantString _imageThatSuppr ...