Map集合的用法


1 Map接口概述

l  Map中的集合,元素是成對存在的(理解為夫妻)。每個元素由鍵與值兩部分組成,通過鍵可以找對所對應的值。

l  Collection中的集合稱為單列集合,Map中的集合稱為雙列集合。

l  需要注意的是,Map中的集合不能包含重復的鍵,值可以重復;每個鍵只能對應一個值。

Map中常用的集合為HashMap集合、LinkedHashMap集合。

 

Map集合的遍歷:

1.keySet

復制代碼
public class Demo01 { public static void main(String[] args) { Map<Integer,String> map=new HashMap<Integer,String>(); //向map中添加鍵值對 map.put(1, "熊大"); map.put(2, "光頭強"); map.put(3, "熊二"); map.put(2, "光頭強"); //根據key獲取value System.out.println(map.get(3)); //刪除 map.remove(1); //遍歷方式1:keySet方法 Set<Integer>set=map.keySet(); for(Integer key:set){ System.out.println(map.get(key)); } Iterator<Integer>it=set.iterator(); while(it.hasNext()){ System.out.println(map.get(it.next())); } }
復制代碼

2.entrySet

復制代碼
public class Demo02 { public static void main(String[] args) { Map<Integer,String> map=new HashMap<Integer,String>(); //向map中添加鍵值對 map.put(1, "熊大"); map.put(2, "光頭強"); map.put(3, "熊二"); map.put(2, "光頭強"); //遍歷方式2:Entry Set<Map.Entry<Integer, String>>set=map.entrySet(); for(Map.Entry<Integer, String>entry:set){ System.out.println(entry.getKey()+"\t"+entry.getValue()); } } }
復制代碼

練習:

Iractor,for和entrySet,keySet遍歷Map集合

 

復制代碼
public class Demo04 { public static void main(String[] args) { Map<GirlFriend,String>map=new HashMap<GirlFriend,String>(); //創建對象 GirlFriend g1=new GirlFriend("吳宣儀",24,166); GirlFriend g2=new GirlFriend("楊超越",21,168); GirlFriend g3=new GirlFriend("朴孝敏",28,167); GirlFriend g4=new GirlFriend("羅玉鳳",34,165); //向map集合中添加key和value map.put(g1, "張三"); map.put(g2, "李四"); map.put(g3, "王五"); map.put(g4, "李四"); //遍歷entrySet+for Set<Map.Entry<GirlFriend,String>>set=map.entrySet(); for(Map.Entry<GirlFriend, String> entry:set){ System.out.println(entry.getKey()+"\t"+entry.getValue()); } System.out.println("==============================="); //entry+iterator Iterator<Map.Entry<GirlFriend, String>>it=set.iterator(); while(it.hasNext()){ Map.Entry<GirlFriend, String>ent=it.next(); System.out.println(ent.getKey()+"\t"+ent.getValue()); } } }
復制代碼
復制代碼
public class Demo03 { public static void main(String[] args) { Map<GirlFriend,String>map=new HashMap<GirlFriend,String>(); //創建對象 GirlFriend g1=new GirlFriend("吳宣儀",24,166); GirlFriend g2=new GirlFriend("楊超越",21,168); GirlFriend g3=new GirlFriend("朴孝敏",28,167); GirlFriend g4=new GirlFriend("羅玉鳳",34,165); //向map集合中添加key和value map.put(g1, "張三"); map.put(g2, "李四"); map.put(g3, "王五"); map.put(g4, "李四"); //KeySet+for Set<GirlFriend>set=map.keySet(); for(GirlFriend g:set){ System.out.println(g+"\t"+map.get(g)); } System.out.println("==================================================="); //KeySet+iterator Iterator<GirlFriend>it=set.iterator(); while(it.hasNext()){ GirlFriend gg=it.next(); System.out.println(gg+"\t"+map.get(gg)); } } }
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM