java基础知识(八)

来源:互联网 发布:复杂网络节点介数 编辑:程序博客网 时间:2024/05/16 15:24
20.map集合①遍历  public class MapDemo {public static void main(String[] args) {Map<String,Student> map=new HashMap<String,Student>();Student s1=new Student("01","Tom");Student s2=new Student("02","Jerry");Student s3=new Student("03","Miss");Student s4=new Student("04","Tony");Student s5=new Student("05","Misa");map.put(s1.getId(), s1);map.put(s2.getId(), s2);map.put(s3.getId(), s3);map.put(s4.getId(), s4);map.put(s5.getId(), s5);//求出所有的键Set<String> key=map.keySet();for(String s:key){System.out.println(s);}//遍历键和值//方法一:迭代System.out.println("迭代遍历:");Iterator it=map.keySet().iterator();while(it.hasNext()){String i=(String) it.next();System.out.println(i+"-"+map.get(i));}//方法二:for-each循环System.out.println("for-each循环遍历:");Set<String> keys=map.keySet();for(String s:keys){System.out.println(s+"-"+map.get(s));}//方法三:使用Entry调用System.out.println("map entry:");Set<Map.Entry<String, Student>> set=map.entrySet();for (Map.Entry<String, Student> entry:set) {System.out.println(entry.getKey()+"-"+entry.getValue());}}  }②map元素不能重复,以键-值对的顺序存储。

0 0
原创粉丝点击