KeySet(): 该方法返回map中所有key值的列表。
Set 是java中一个存储不重复元素,且无序的集合类。
Map.keyset(),表示将map对象的所有key值已set集合的形式返回,因为map也是无序的,且key值也是不可重复的,因此这里用set集合存储key并返回也符合规则。
将Map中所有的键存入到set集合中。因为set具备迭代器。所有可以迭代方式取出所有的键,再根据get方法。获取每一个键对应的值。 keySet():迭代后只能通过get()取key
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");
Set<String> mpKey = map.keySet();
System.out.println(mpKey );
输出结果:
[xiaocui4, xiaocui1, xiaocui2, xiaocui3]