1.Map中提供给了一些常用方法,如keySet()、value()、entrySet()用于取出元素
keySet()方法:返回此映射中所包含的键的 set 视图(集合)
public Set<K> keySet()
value()方法:返回此映射所包含的值的 collection 视图
public Collection<V> values()
entrySet()方法:返回此映射所包含的映射关系的 collection 视图(这边有点疑问:因为事实上返回的是Set),在返回的集合中,每个元素都是一个Map.Entry
public Set<Map.Entry<K,V>> entrySet()
一个具体的例子:
class HelloWorld{public static void main(String[] args){HashMap<String,String> map = new HashMap<String,String>();map.put("1","one");map.put("2","two");map.put("3", "tree");map.put("4", "four");//使用keySet方法,取出所有的键组成Set集合System.out.println(map.keySet());//使用values方法,取出所有的值组成的CollectionSystem.out.println(map.values());//entrySet()方法,取出 所有的键-值组成Set集合System.out.println(map.entrySet());}}
程序运行结果打印如下,可以看到分别返回所有的键、所有的值和所有的键-值的组合:
两次遍历,效率最差
[3, 2, 1, 4][tree, two, one, four][3=tree, 2=two, 1=one, 4=four]
2.如何将Map中的键,值取出,有三种常见的方法:
第一种方法:是先通过keySet()方法取出键,再通过迭代分别取出对应的值
class HelloWorld{public static void main(String[] args){HashMap<String,String> map = new HashMap<String,String>();map.put("01", "zhangsan");map.put("02", "lisi");map.put("03", "wangwu");Set<String> set = map.keySet();//得到由键组成的Set集合Iterator<String> it = set.iterator();while(it.hasNext()){String key = it.next();String value = map.get(key);//通过get方法,获取键对应的值System.out.println(key+" "+value);//将键和值都打印出来}}}
第二种方法:
class HelloWorld{public static void main(String[] args){HashMap<String,String> map = new HashMap<String,String>();map.put("01", "zhangsan");map.put("02", "lisi");map.put("03", "wangwu");Set<Map.Entry<String,String>> entry = map.entrySet();//得到包含映射关系的collecton视图Iterator<Map.Entry<String, String>> it = entry.iterator();while(it.hasNext()){Map.Entry<String,String> me = it.next();System.out.println(me.getKey()+" "+me.getValue());//通过getKey()得到键}//通过getValue()得到值}}说明:在返回的Set集合中,每个元素都是一个 Map.Entry,再通过iteraor来访问该集合,得到每个Map.Entry元素,最后通过getKey()和getValue()方法得到键和值
第二种方式可以不用迭代器,直接遍历Entry对象
class HelloWorld{public static void main(String[] args){HashMap<String,String> map = new HashMap<String,String>();map.put("01", "zhangsan");map.put("02", "lisi");map.put("03", "wangwu");for(Map.Entry<String, String> entry: map.entrySet()){ System.out.println(entry.getKey() + entry.getValue()); }}}第三种方法(这个方法只能取出值):
class HelloWorld{public static void main(String[] args){HashMap<String,String> map = new HashMap<String,String>();map.put("01", "zhangsan");map.put("02", "lisi");map.put("03", "wangwu");Collection<String> collection = map.values(); //通过values方法得到包含所有值Collection视图Iterator<String> it = collection.iterator();while(it.hasNext()){String name = it.next();System.out.println(name); //打印出所有的值}}}
免责声明:文章源自网络,版权归原作者所有,如有侵犯联系删除。