对Map的键值对操作

来源:互联网 发布:我的世界java是什么 编辑:程序博客网 时间:2024/05/01 20:39
public static void main(String[] args) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("1", "apple");
        map.put("2", "orange");
        map.put("3", "pear");
        map.put("4", "grape");
        map.put("5", "coconut");
        //先获取Map中的所有key值,然后根据key,依次从Map中去数据
        Set<String> set = map.keySet();
        for (String key:set) {
            System.out.println(key+":"+map.get(key));
        }
        System.out.println("===============================");
        //对应的还有一个 Set<Map.Entry<K, V>> entrySet();Map中的每条key-value数据对应着一个Entry,
        Set<Map.Entry<String, String>> entries = map.entrySet();
        //使用增强新for循环
        
        /*for (Entry<String, String> entry:entries) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }*/
        
        //使用迭代器
        Iterator<Entry<String, String>> it = entries.iterator();
        while(it.hasNext()){
            Entry<String, String> entry = it.next();
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
        
        
    }
0 0
原创粉丝点击