關於map集合的遍歷
阿新 • • 發佈:2018-12-19
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Main { /** * * 關於map集合的遍歷 */ public static void main(String[] args) { System.out.println("Hello World!"); // function01(); //function02(); //function03(); function04(); } /** *第一種遍歷map集合的方法 * 通過map集合的keyset()方法來得到鍵的集合 */ public static void function01(){ Map<Integer, String> map = new HashMap<>(); map.put(1,"一"); map.put(2,"二"); map.put(3,"三"); map.put(4,"四"); map.put(5,"五"); map.put(6,"六"); Set<Integer> set = map.keySet(); for(Integer in:set){ System.out.println(in+":"+map.get(in)); } } /** * 第二種方法:通過map的entryset() */ public static void function02(){ Map map = new HashMap<Integer,String>(); map.put(1,"一"); map.put(2,"二"); map.put(3,"三"); map.put(4,"四"); map.put(5,"五"); map.put(6,"六"); Set<Map.Entry<Integer,String>> set = map.entrySet(); for(Map.Entry<Integer,String> entry:set){ System.out.println("key鍵為:"+entry.getKey()+"values為:"+entry.getValue()); } } /** * 第三種方法:使用iterator */ public static void function03(){ Map map = new HashMap<Integer,String>(); map.put(1,"一"); map.put(2,"二"); map.put(3,"三"); map.put(4,"四"); map.put(5,"五"); map.put(6,"六"); Iterator<Map.Entry<Integer,String>> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<Integer, String> next =iterator.next(); System.out.println("key為:"+next.getKey()+"value為:"+next.getValue()); } } /** * 第四種方法:使用map的values()方法: */ public static void function04(){ Map map = new HashMap<Integer,String>(); map.put(1,"一"); map.put(2,"二"); map.put(3,"三"); map.put(4,"四"); map.put(5,"五"); map.put(6,"六"); for (Object value : map.values()) { System.out.println("value為:"+value); } ; } }