Java的Map中的map.keySet()方法

时间:2021-06-11 17:54:13

该方法返回map中所有key值的列表。

今天再代码中看到了Map集合中的HashMap的map.keySet()方法,首先看一下这个方法的定义

    /**
     * Returns a {@link Set} view of the keys contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own <tt>remove</tt> operation), the results of
     * the iteration are undefined.  The set supports element removal,
     * which removes the corresponding mapping from the map, via the
     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
     * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
     * operations.
     *
     * @return a set view of the keys contained in this map
     */
		Set<K> keySet();

大致的意思描述如下:

1)返回此映射中包含的键的 Set视图。

2)这个 set 受到映射支持,所以对映射的更改可在此 set 中反映出来,反之亦然。

3)如果对该 set 进行迭代的同时修改了映射(通过迭代器自己的 remove 操作除外),则迭代结果是不确定的。

4)set 支持元素移除,通过 Iterator.remove、 Set.remove、 removeAll、retainAll 和 clear 操作可从映射中移除(删除)相应的映射关系。

5)set不支持 add 或 addAll 两种添加操作。

6)返回值是:map包含的键的 set 视图
代码的使用:

Map<Integer, String> map = new HashMap<>();
//下面可以使用map.keySet()方法
map.keySet();

测试代码:

public class SourceCode {
    public static void main(String[] args) {

        Map<String,String> map = new HashMap<String, String>();

        map.put("xiaocui1","gongchen");
        map.put("xiaocui2","daima");
        map.put("xiaocui3","xuexi");
        map.put("xiaocui4","dagong");

        System.out.println(map.keySet());

        System.out.println("-----分割线-----");
        for(String map1 : map.keySet()){
            String string = map.keySet().toString();
            System.out.println(string);
        }
    }
}

输出结果:

[xiaocui4, xiaocui1, xiaocui2, xiaocui3]
-----分割线-----
[xiaocui4, xiaocui1, xiaocui2, xiaocui3]
[xiaocui4, xiaocui1, xiaocui2, xiaocui3]
[xiaocui4, xiaocui1, xiaocui2, xiaocui3]
[xiaocui4, xiaocui1, xiaocui2, xiaocui3]