测试程序如下:
1:获取键值4种:entrySet: 2种(foreach,iterator) 和 keySet+get: 2种(foreach,iterator)
/** * 获取键与值 */ public static void iterEntry(Map<String,Students> map){ System.out.println("======entrySet 2种========"); Set<Map.Entry<String, Students>> entrySet =map.entrySet(); System.out.println("1==foreach========"); for(Map.Entry<String, Students> temp:entrySet){ String key =temp.getKey(); Students value =temp.getValue(); System.out.println(key+"-->"+value); } System.out.println("2==iterator========"); Iterator<Map.Entry<String, Students>> it =entrySet.iterator(); while(it.hasNext()){ Map.Entry<String, Students> temp =it.next(); String key =temp.getKey(); Students value =temp.getValue(); System.out.println(key+"-->"+value); } System.out.println("======keySet+get 2种========"); Set<String> keySet =map.keySet(); System.out.println("1==foreach========"); for(String key:keySet){ Students value =map.get(key); System.out.println(key+"-->"+value); } System.out.println("2==iterator========"); Iterator<String> keyIt =keySet.iterator(); while(keyIt.hasNext()){ String key =keyIt.next(); Students value =map.get(key); System.out.println(key+"-->"+value); } }
2.获取键4种方法:entrySet: 2种(foreach,iterator) 和 keySet+get: 2种(foreach,iterator)
public static void iterKeys(Map<String,Students> map){ System.out.println("======entrySet 2种========"); Set<Map.Entry<String, Students>> entrySet =map.entrySet(); System.out.println("1==foreach========"); for(Map.Entry<String, Students> temp:entrySet){ String key =temp.getKey(); System.out.println(key); } System.out.println("2==iterator========"); Iterator<Map.Entry<String, Students>> it =entrySet.iterator(); while(it.hasNext()){ Map.Entry<String, Students> temp =it.next(); String key =temp.getKey(); System.out.println(key); } System.out.println("======keySet+get 2种========"); Set<String> keySet =map.keySet(); System.out.println("1==foreach========"); for(String key:keySet){ System.out.println(key); } System.out.println("2==iterator========"); Iterator<String> keyIt =keySet.iterator(); while(keyIt.hasNext()){ String key =keyIt.next(); System.out.println(key); } }
3.获取值6种方法: entrySet 2种,keySet+get 2种,values() 2种
public static void iterValues(Map<String,Students> map){ System.out.println("======entrySet 2种========"); System.out.println("======keySet+get 2种========"); System.out.println("======values() 2种========"); Collection<Students> values =map.values(); System.out.println("1==foreach========"); for(Students p:values){ System.out.println(p); } System.out.println("2==iterator========"); Iterator<Students> it =values.iterator(); while(it.hasNext()){ Students p =it.next(); System.out.println(p); }