文章目录 Map概述 Map常用方法 Map遍历元素的方法 1.方法一:keySet() 2.方法二:entrySet() HashMap
Map概述
1、Map和collection没有继承关系 2、Map集合以key和value的方式存储数据:键值对 key和value都是引用数据类型。 key和value都是存储对象的内存地址。 key起到主导的地址,value是key的一个附属品。
Map常用方法
V put(K key,V value) 向Map集合中添加键值对 V get(Object key) 通过Key获取value void clear() 清空Map集合 boolean containsKey(Object key) 判断Map中是否包含某个Key boolean containsValue(Object value) 判断Map中是否包含某个value boolean isEmpty() 判断Map集合中元素个数是否为0 V remove(Object key) 通过key删除键值对 int size() 获取Map集合中键值对的个数 Set keySet() 获取Map集合中所有的key(所有的键是一个set集合) Collection values() 获取Map集合中所有的value,返回一个Collection Set<Map.Entry<K,V> entrySet> 将Map集合转换成Set集合遍历key-value
public class MapTest01 { public static void main ( String [ ] args) { Map < Integer , String > map = new HashMap < > ( ) ; map. put ( 101 , "zhangsan" ) ; map. put ( 202 , "lisi" ) ; map. put ( 303 , "wangwu" ) ; map. put ( 404 , "zhaoliu" ) ; System . out. println ( "2.Map中所有键值对的个数:" + map. size ( ) ) ; String value = map. get ( 303 ) ; System . out. println ( "3.通过key取到的value为:" + value) ; Collection < String > values = map. values ( ) ; System . out. println ( "4.values()获取Map中的所有value:" + values) ; for ( String str : values) { System . out. println ( "5.遍历取出:" + str) ; } Set < Integer > keys = map. keySet ( ) ; System . out. println ( "9.keySet()返回Map中所有的key:" + keys) ; System . out. println ( "7.判断是否包含202的key的结果为:" + map. containsKey ( 202 ) ) ; System . out. println ( "8.判断是否包含zhaoliu的value的结果为:" + map. containsValue ( "leilei" ) ) ; map. remove ( 404 ) ; System . out. println ( "6.调用remove()方法后的键值对的数量:" + map. size ( ) ) ; map. clear ( ) ; System . out. println ( "10.clear()后键值对的数量为:" + map. size ( ) ) ; }
}
Map遍历元素的方法
1.方法一:keySet()
public class MapTest02Foreach { public static void main ( String [ ] args) { Map < Integer , String > map = new HashMap < > ( ) ; map. put ( 101 , "zhangsan" ) ; map. put ( 202 , "lisi" ) ; map. put ( 303 , "wangwu" ) ; map. put ( 404 , "zhaoliu" ) ; Set < Integer > keys = map. keySet ( ) ; Iterator < Integer > it = keys. iterator ( ) ; while ( it. hasNext ( ) ) { Integer key = it. next ( ) ; String value = map. get ( key) ; System . out. println ( "Iterator遍历:" + value) ; } for ( Integer key : keys) { System . out. println ( "foreach遍历:" + map. get ( key) ) ; } }
}
2.方法二:entrySet()
public class MapTest02Foreach { public static void main ( String [ ] args) { Map < Integer , String > map = new HashMap < > ( ) ; map. put ( 101 , "zhangsan" ) ; map. put ( 202 , "lisi" ) ; map. put ( 303 , "wangwu" ) ; map. put ( 404 , "zhaoliu" ) ; Set < Map. Entry < Integer , String > > entry = map. entrySet ( ) ; Iterator < Map. Entry < Integer , String > > it1 = entry. iterator ( ) ; while ( it1. hasNext ( ) ) { Map. Entry < Integer , String > node = it1. next ( ) ; Integer key = node. getKey ( ) ; String value = node. getValue ( ) ; System . out. println ( key+ "-->" + value) ; } for ( Map. Entry < Integer , String > node1 : entry) { System . out. println ( node1) ; } }
}
HashMap