Map遍历的几种形式
Map遍历的几种方式
几种常见的map集合遍历方式
在遍历时使用到set,因此遍历的顺序是与hashcode有关的
几种常见的map集合遍历方式
在遍历时使用到set,因此遍历的顺序是与hashcode有关的
Map<String,String> m = new HashMap<String,String>(); m.put("one", "hello world one!"); m.put("two", "hello world two!"); m.put("three", "hello world three!"); m.put("four", "hello world four!"); System.out.println("==================num 1======================"); ArrayList l = new ArrayList(m.entrySet());//使用一个Collection来初始化这个List; for(int i=0;i<l.size();i++ ){ System.out.println(((Map.Entry)l.get(i)).getValue()); } System.out.println("====================num 2======================"); //使用的是Set而set是不对key的顺序负责的内部使用hashcode确定存储位置不同 Set key = m.keySet(); for(Iterator it = key.iterator();it.hasNext();){ String mykey= (String)it.next(); if(mykey.equals("one")){ System.out.println(mykey+" "+m.get(mykey)); } } System.out.println("====================num 3======================"); //使用这种方式,要对map对象进行泛型的规定 for(Map.Entry<String, String> my:m.entrySet()){ System.out.println(my.getKey()+" "+my.getValue() ); }