本文主要是介绍HashMap遍历之EntrySet,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
entry可以获取key和value的具体值
当entry<key,value>
public static void main(String[] args) {Map map = new HashMap();map.put("邓超", "孙俪");//替换map.put("王宝强", "马蓉");//okmap.put(null, "刘亦菲");//plmap.put("鹿晗", null);//okmap.put("lu汉", "刘亦菲");map.put("沫年", "刘亦菲");//okSystem.out.println(map);System.out.println("\n==========迭代器===========\n");Iterator ito3 = entrySet.iterator();while(ito3.hasNext()){Map.Entry entry2 = (Map.Entry) ito3.next();System.out.println(entry2.getValue());}// Iterator ito3 = entrySet.iterator();
// while(ito3.hasNext()){
// Object entry = ito3.next();System.out.println(entry);//HashMap$Node ---实现 > Map.Entry (getKey,getValue)
// //向下转型 Map.Entry
// Map.Entry m = (Map.Entry) entry;
// System.out.print(m.getValue()+" ");
// }}
当entry<key,Object>,此时value = Object
public static void main(String[] args) {/*** 使用HashMapp添加三个员工对象,要求* 键:员工id* 值:员工对象** 并且遍历显示工资>18000的员工(遍历方式最少两种)* 员工类:姓名、工资、员工id*/Map map = new HashMap();map.put(1, new Employee("smith", 18000, "20001206"));map.put(2, new Employee("tom", 28000, "20011212"));map.put(3, new Employee("smith", 10000, "20111010"));System.out.println("员工的个数为:" + map.size());System.out.println("=========第三种遍历方式=========");Set set = map.entrySet();//先将map转化为entrySetIterator ito2 = set.iterator();//构建迭代器while (ito2.hasNext()){//迭代器循环条件Map.Entry entry = (Map.Entry) ito2.next();//将entrySet 转化为entry,并且向下移动指针//通过entry来获取key和valueEmployee emp = (Employee) entry.getValue();//将包entry向下转型为EmployeeSystem.out.println(emp);}
}
这篇关于HashMap遍历之EntrySet的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!