第一種:java
最常規的一種遍歷方法,最常規就是最經常使用的,雖然不復雜,但很重要,這是咱們最熟悉的。spa
- import java.util.Collection;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.HashMap;
-
-
- public class TraversalMap1 {
- private static Map<Integer, String> map;
- private static TraversalMap1 getMap(){
- map = new HashMap<Integer, String>();
- for(int i = 0 ; i < 10 ; i ++){
- if(map.isEmpty()) map.put(i, "String " + i);
- else if(map.get(i) == null) map.put(i,"String " + i) ;
- }
- return null;
- }
-
- public static void main(String[] args){
- getMap();
- Collection<String> c = map.values();
- Iterator i = c.iterator();
- for(; i.hasNext() ;){
- System.out.println(i.next());
- }
-
- }
- }
第二種:對象
利用keyset進行遍歷,它手優勢在於能夠根據你所想要的key值獲得你想要的values,更具靈活性。get
- import java.util.Set;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.HashMap;
-
- public class TraversalMap2 {
- private static Map<Integer, String> map;
- private static TraversalMap2 getMap(){
- map = new HashMap<Integer, String>();
- for(int i = 0 ; i < 10 ; i ++){
- if(map.isEmpty()) map.put(i, "String " + i);
- else if(map.get(i) == null) map.put(i,"String " + i) ;
- }
- return null;
- }
-
- public static void main(String[] args){
- getMap();
- Set set = map.keySet();
- Iterator i = set.iterator();
- for(; i.hasNext() ;){
- System.out.println(i.next());
- }
-
- }
- }
第三種:string
比較複雜的一種遍歷在這裏,呵呵~~它很暴力哦,它的靈活性太強了,想獲得什麼就能獲得什麼~~it
- import java.util.Map;
- import java.util.HashMap;
-
- public class TraversalMap3 {
- private static Map<Integer, String> map;
- private static int num = 0 ;
- private static String str = "";
- private static TraversalMap3 getMap(){
- map = new HashMap<Integer, String>();
- for(int i = 0 ; i < 10 ; i ++){
- if(map.isEmpty()) map.put(i, "String " + i);
- else if(map.get(i) == null) map.put(i,"String " + i) ;
- }
- return null;
- }
-
- public static void main(String[] args){
- getMap();
- for(Map.Entry<Integer, String> entry : map.entrySet()){
- num = entry.getKey();
- str = entry.getValue();
- System.out.println("the map key is : " + num + " || the value is : " + str);
- }
-
- }
- }