标签:
// 创建集合对象 HashMap<Teacher, String> hm = new HashMap<Teacher, String>(); // 创建元素 Teacher t1 = new Teacher("小明", 19); Teacher t2 = new Teacher("小刚", 15); Teacher t3 = new Teacher("小强", 23); Teacher t4 = new Teacher("小周", 20); Teacher t5 = new Teacher("小明", 19); // 添加元素 hm.put(t1, "001"); hm.put(t2, "003"); hm.put(t3, "002"); hm.put(t4, "004"); hm.put(t5, "005"); // 遍历 Set<Map.Entry<Teacher, String>> set = hm.entrySet(); Iterator<Map.Entry<Teacher, String>> it = set.iterator(); while (it.hasNext()) { Map.Entry<Teacher, String> me = it.next(); Teacher key = me.getKey(); String value = me.getValue(); System.out.println(key.getName() + "***" + key.getAge() + "***" + value); }
// 创建Map集合对象 Map<String, String> hm = new HashMap<String, String>(); // 创建元素并添加元素 hm.put("it002", "hello"); hm.put("it003", "world"); hm.put("it001", "java"); hm.put("it004", "itcast"); hm.put("it002", "javaee"); //System.out.println("get:"+hm.get("it003")); //获取所有键的集合 Set<String> set = hm.keySet(); Iterator<String> it = set.iterator(); while(it.hasNext()){ String key = it.next(); System.out.println(key); } System.out.println("**************************************"); Collection<String> coll = hm.values(); //返回的是Collection子类对象 Iterator<String> it2 = coll.iterator(); while(it2.hasNext()){ String value = it2.next(); System.out.println(value); } System.out.println("**************************************"); //Map的遍历 //获取所有键的集合 Set<String> keySet = hm.keySet(); Iterator<String> keyIt = keySet.iterator(); //通过迭代器遍历键的集合,获取到每一个键值 while(keyIt.hasNext()){ //获取到每一个键 String key = keyIt.next(); //根据键获取对应的值 String value = hm.get(key); System.out.println(key+":"+value); } System.out.println("**************************************"); //Set<Map.Entry<K,V>> entrySet() //获取所有键值对的集合 Set<Map.Entry<String,String>> entrySet = hm.entrySet(); Iterator<Map.Entry<String,String>> entryIt = entrySet.iterator(); //遍历键值对的集合,获取每一个键值对对象 while(entryIt.hasNext()){ Map.Entry<String,String> me = entryIt.next(); //返回的是实现了该接口的子类对象 //获取键 String key = me.getKey(); //获取值 String value= me.getValue(); System.out.println(key+":"+value); }
标签:
原文地址:http://www.cnblogs.com/52hadoop/p/4386840.html