java中的集合之map集合

編程語言 Java 技術 二環十三郎 2017-04-02

Map

雙列集合:

-------------| Map 如果是實現了Map接口的集合類,具備的特點: 存儲的數據都是以鍵值對的形式存在的,鍵不可重複,值可以重複。

----------------| HashMap

----------------| TreeMap

----------------| Hashtable

Map接口的方法:

添加:

put(K key, V value)添加元素 如果之前沒有存在該鍵,那麼返回的是null,如果之前就已經存在該鍵了,那麼就返回該鍵之前對應 的值。

putAll(Map<? extends K,? extends V> m)

刪除

remove(Object key)指定根據key值刪除

clear() 刪除所有元素

獲取:

get(Object key)根據key獲取值,

size()

判斷:

containsKey(Object key)判斷map集合是否包含指定的鍵

containsValue(Object value)判斷map集合是否包含指定的值

isEmpty() 判斷map是否為空

*/

publicclass Map01 {

publicstaticvoid main(String[] args) {

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

//添加元素

map.put("1", "葉輝");

map.put("2", "戰三");

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

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

map2.put("3", "張飛");

map2.put("5", "張歡");

map.putAll(map2);//把map2的元素添加到map集合中。

//指定刪除元素、

//map.remove("1");

//刪除所有元素

//map.clear();

System.out.println(map.get("1"));

}

迭代:

keySet()把Map集合中的所有鍵都保存到一個Set類型的集合對象中返回。 缺點: keySet方法只是返回了所有的鍵,沒有值。Set<K> keySet():獲取集合中所有鍵的集合

values()把所有的值存儲到一個Collection集合中返回,Collection<V> values():獲取集合中所有值的集合。 缺點: values方法只能返回所有 的值,沒有鍵。

entrySet()這種方法既能夠獲取鍵又能夠獲取值

*/

publicclass Map02 {

publicstaticvoid main(String[] args) {

//創建一個map對象

Map<Integer,String> map= new HashMap<Integer,String>();//泛型只能放封裝類

map.put(1, "葉輝");

map.put(2, "張三");

map.put(3, "李四");

map.put(4, "王五");

map.put(5, "王二");

/* //方式一:查詢

Set<Integer> setMap = map.keySet();

//迭代器

Iterator<Integer> it = setMap.iterator();

while(it.hasNext()){

int key = it.next();

System.out.println("鍵:"+key+" "+"值:"+map.get(key));

}*/

/* //方式二:

Collection<String> c= map.values();

//迭代器遍歷

Iterator<String> it = c.iterator();

while(it.hasNext()){

String Value =it.next();

System.out.println("值:"+Value);

}*/

//方式3:

Set<Map.Entry<Integer,String>> entrys = map.entrySet();

//迭代器

Iterator<Map.Entry<Integer,String>> it = entrys.iterator();

while(it.hasNext()){

Map.Entry<Integer,String> en = it.next();

System.out.println("鍵值:"+en.getKey()+" "+"值:"+en.getValue());

}

}

相關推薦

推薦中...