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

该方法返回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]
  • 18
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 22
    评论
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值