1.Map集合简介:map集合是一个key—value型的数据结构,存储的数据具有查询速度快速的特点,但由于是无序的,所以没有顺序可言。在遍历时没有办法像简单的list或数组一样。
2.代码:
1 package com.cn.testmap; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 import java.util.Map.Entry; 7 8 /** 9 * map的4种便历方法操作 10 * @author lenovo 11 * 12 */ 13 14 public class Maptest { 15 private static Map<String,String> map = new HashMap<String,String>(); 16 public static void main(String[] args) { 17 map.put("name", "李四"); 18 map.put("age", "30"); 19 map.put("sex", "male"); 20 map.put("code", "3010"); 21 //方法一:通过key取值 22 /*for(String key:map.keySet()){ 23 System.out.printf("map key is %s and value is %s",key,map.get(key)); 24 System.out.println(); 25 }*/ 26 //方法二:通过迭代器取值 27 /*Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator(); 28 Entry<String, String> entry = null; 29 while(iterator.hasNext()){ 30 entry = iterator.next(); 31 System.out.printf("key is %s and value is %s",entry.getKey(),entry.getValue()); 32 System.out.println(); 33 }*/ 34 //通过entryset 35 /*for(Entry<String, String> entry:map.entrySet()){ 36 System.out.printf("key is %s and value is %s",entry.getKey(),entry.getValue()); 37 System.out.println(); 38 }*/ 39 //通过map的value方法实现 40 for(String value : map.values()){ 41 System.out.println("value is "+value); 42 } 43 } 44 }