java map遍曆的四種方法總結_java

來源:互聯網
上載者:User

整理了關於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=第一個數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.