通过java增强for循环for each遍历Map中的数据
来源:互联网 发布:数据库云平台 编辑:程序博客网 时间:2024/05/16 00:55
首先取得Map中的数据方法如下图所示,在java普通的for循环当中,一般是按照如下图1,图2的方法,现将Map的keyset或者entrySet保存在一个set集合当中,然后对set集合使用iterator迭代器,进行迭代循环。但是今天要介绍的是使用增强for循环for each进行对Map中数据元素进行迭代。
第一种:
@Testpublic void test() {Map<Integer, String> map=new HashMap<Integer, String>();map.put(1, "this is 1");map.put(2, "this is 2");map.put(3, "this is 3");map.put(4, "this is 4");for (Object obj : map.keySet()) {String key= (String) obj;String value = map.get(key);System.out.println("key is "+key+"value is "+value);}}
第二种:
@Testpublic void test2() {Map<Integer, String> map=new HashMap<Integer, String>();map.put(1, "this is 1");map.put(2, "this is 2");map.put(3, "this is 3");map.put(4, "this is 4");for (Object obj : map.entrySet()) {//将取得的map的entryset保存Map.Entry entry= (Entry) obj;String key=entry.getKey().toString();String value=(String) entry.getValue();System.out.println("key is "+key+"value is:" +value);}}
主要思路就是keySet属性,还有entrySet属性继承了迭代器的接口。所以只要实现了迭代器的接口的数据类型,都可以用增强for循环取除数据。虽然Map没有实现迭代器接口。但是Map中的set集合取出之后就可以迭代了。进而何以使用增强for循环了。
下面是全部代码。
package Demo;import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import org.junit.Test;public class demo {@Testpublic void test() {Map<Integer, String> map=new HashMap<Integer, String>();map.put(1, "this is 1");map.put(2, "this is 2");map.put(3, "this is 3");map.put(4, "this is 4");for (Object obj : map.keySet()) {String key= (String) obj;String value = map.get(key);System.out.println("key is "+key+"value is "+value);}}@Testpublic void test2() {Map<Integer, String> map=new HashMap<Integer, String>();map.put(1, "this is 1");map.put(2, "this is 2");map.put(3, "this is 3");map.put(4, "this is 4");for (Object obj : map.entrySet()) {//将取得的map的entryset保存Map.Entry entry= (Entry) obj;String key=entry.getKey().toString();String value=(String) entry.getValue();System.out.println("key is "+key+"value is:" +value);}}}
- 通过java增强for循环for each遍历Map中的数据
- 【for-each】增强for循环
- java增强for循环遍历Map集合问题
- JAVA使用增强for循环和迭代器遍历Map集合
- Java使用增强for循环和迭代器遍历Map集合
- JAVA中的for each循环
- java中的for each循环
- java中的for each循环
- java中的for each循环
- java中的for each循环
- for-each遍历Map
- 增强for循环和for-each循环
- Java学习笔记:for-each增强for循环
- Java 增强型的for循环 for each
- java 增强型的for循环 for each
- Java 增强型的for循环 for each
- Java 增强型的for循环 for each 【转载】
- Java 增强型的for循环 for each
- Hdu递推求解专题练习(For Beginner)
- mac ftp server
- 杭电1004
- Luhn 算法
- 种类并查集-POJ-1184
- 通过java增强for循环for each遍历Map中的数据
- C语言经典例题100道 第三题
- 关闭 SSMS IntelliSense
- Windows 获取当前系统时间函数总结
- ibatis的用法简介
- ClassLoader 学习笔记
- JS延迟加载百度分享代码,提高网页速度
- LISP 8.5 宏形参
- Android如何通过无线网络连接adb