zoukankan      html  css  js  c++  java
  • 整理java map遍历的四种方法

    整理了关于java中map的遍历的四种方法:

    import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;import java.util.Set;publicclassMapTest{privateMap<String,String> map;publicMapTest(){
    		map =newHashMap<String,String>();
    		map.put("1","第一个数");
    		map.put("2","第二个数");
    		map.put("3","第三个数");}// 第一种方法(传统方法)publicvoid mapOne(){Set<String> set = map.keySet();Iterator<String> it = set.iterator();while(it.hasNext()){String key =(String) it.next();String value =(String) map.get(key);System.out.println(key +"="+ value);}}// 第二种方法(传统方法)publicvoid mapTwo(){Set set = map.entrySet();Iterator it = set.iterator();while(it.hasNext()){Entry entry =(Entry) it.next();String key =(String) entry.getKey();String value =(String) entry.getValue();System.out.println(key +"="+ value);}}// 第三种方法(增强for循环方法)publicvoid mapThree(){for(Object obj : map.keySet()){String key =(String) obj;String value =(String) map.get(key);System.out.println(key +"="+ value);}}// 第四种方法(增强for循环方法)publicvoid mapFour(){for(Object obj : map.entrySet()){Entry entry =(Entry) obj;String key =(String) entry.getKey();String value =(String) entry.getValue();System.out.println(key +"="+ value);}}publicstaticvoid main(String[] args){MapTest mapTest =newMapTest();System.out.println("=====first=====");
    		mapTest.mapOne();System.out.println("=====second=====");
    		mapTest.mapTwo();System.out.println("=====three=====");
    		mapTest.mapThree();System.out.println("=====four=====");
    		mapTest.mapFour();}}

    输出结果:

    =====first=====3=第三个数2=第二个数1=第一个数=====second=====3=第三个数2=第二个数1=第一个数=====three=====3=第三个数2=第二个数1=第一个数=====four=====3=第三个数2=第二个数1=第一个数
  • 相关阅读:
    UVa 1354 天平难题 (枚举二叉树)
    广西邀请赛总结
    UVa 12118 检查员的难题 (dfs判连通, 构造欧拉通路)
    UVA
    Uva 127 "Accordian" Patience (模拟)
    UVA 10539 Almost Prime Numbers( 素数因子)
    HDU 1272 小希的迷宫(并查集)
    HDU 1213 How Many Tables (并查集)
    POJ 2236 Wireless Network(并查集)
    HDU 1233 还是畅通工程 ( Kruskal或Prim)
  • 原文地址:https://www.cnblogs.com/haohai/p/2721902.html
Copyright © 2011-2022 走看看