import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class MapSetEntryTest { public static void main(String[] args) { //定义一个Map集合并赋值 Map<String, String> map = new HashMap<>(); map.put("aaa", "AAA"); map.put("bbb", "BBB"); map.put("ccc", "CCC"); map.put("ddd", "DDD"); map.put("eee", "EEE"); map.put("fff", "FFF"); Set<Entry<String, String>> set = map.entrySet(); Iterator<Entry<String, String>> ite = set.iterator(); while(ite.hasNext()){ Entry<String, String> entry = ite.next(); System.out.println(entry); System.out.println(entry.getKey()); System.out.println(entry.getValue()); System.out.println("************************"); } } }
运行结果:
aaa=AAA aaa AAA ************************ ccc=CCC ccc CCC ************************ bbb=BBB bbb BBB ************************ eee=EEE eee EEE ************************ ddd=DDD ddd DDD ************************ fff=FFF fff FFF ************************此方法效率比keySet()高