Map迭代器的使用方法

public static void main(String[] args) {
		        Map<String,Object> map = new HashMap<String,Object>();
		        map.put("one", "第一");
		        map.put("two", "第二");
		        map.put("three", "第三");
		        map.put("h", "憨憨");
		         
		        //1、迭代器
		        Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();
		        //判断往下还有没有数据
		        while(iter.hasNext()){
		            //有的话取出下面的数据
		            Entry<String, Object> entry = iter.next();
		            String key = entry.getKey();
		            String value = (String)entry.getValue();
		            if("h".equals(entry.getKey())){
		                System.out.println("这个是憨憨");
		            }
		            System.out.println(key + " :" + value);
		        }
		         
		        //2、foreach循环
		        //获取key + value
		        for (Object key : map.keySet()) {
		            String value = (String)map.get(key);
		            System.out.println(key + " : " + value);
		        }
		        //获取value
		        for (Object value : map.values()) {
		            System.out.println(value);
		        }
		         
		        //3、当容量特别大的时候
		        for (Entry<String, Object> entry : map.entrySet()) {
		             System.out.println(entry.getKey() + " : " + entry.getValue());
		        }
	}

LinkedHashMap.keySet()默认是按原序排序的

Hashtable.keySet()默认是按降序排序的

HashMap.keySet()默认是按乱序排序的

TreeMap.keySet()默认是升序排序的

发布了27 篇原创文章 · 获赞 1 · 访问量 1326

猜你喜欢

转载自blog.csdn.net/Sakitaf/article/details/104486928