Map集合

Map集合

概念

Map集合提供了集合之间一种映射关系,让集合和集合之间产生关系。

特点

  • 能够存储唯一的列的数据(唯一,不可重复) Key值。
  • 能够存储可以重复的数据(可重复) value值。
  • 值的顺序取决于键的顺序。
  • 键和值都是可以存储null元素的。
  • 一个映射不能包含重复的键,每个键最多只能映射到一个值。

常用方法

1.添加功能

  • V put(K key, V value)
  • void putAll(Map<? extends K,? extends V> m)

2.删除功能

  • V remove(Object key)
  • void clear()

3.遍历功能

  • Set
  • Collection
  • Set<Map.Entry<K,V> entrySet()

4.获取功能

  • V get(Object key)

5.判断功能

  • boolean containsKey(Object key)
  • boolean containsValue(Object value)
  • boolean isEmpty()

6.修改功能

  • V put(K key, V value)
  • void putAll(Map<? extends K,? extends V> m)

7.长度功能

  • int size()

遍历方式

  • 方式1:根据Key查找Value
    Set<Key> set = map.keySet()
    • 获取所有Key的集合 。
    • 遍历Key的集合,获取到每一个Key 。
    • 根据Key查找Value。
public class Test {
	public static  void main(String[] args) {
		Map<String,Integer> map = new HashMap<String,Integer>();
		map.put("张三", 18);
		map.put("李四", 19);
		map.put("王五", 18);
		map.put("赵六", 21);
		Set<String> ks = map.keySet();
		for(String s:ks){
			Integer i = map.get(s);
			System.out.println("姓名:"+s+"	年龄:"+i);
		}
	}
}
  • 方式2:根据键值对对象找键和值
    Set<Map.Entry<Key, Value>> set = map.entrySet();
    • 获取所有键值对对象的集合。
    • 遍历键值对对象的集合,获取到每一个键值对对象。
    • 根据键值对对象找键和值。
public class Test {
	public static  void main(String[] args) {
		Map<String,Integer> map = new HashMap<String,Integer>();
		map.put("张三", 18);
		map.put("李四", 19);
		map.put("王五", 18);
		map.put("赵六", 21);
		Set<Entry<String,Integer>> mks = map.entrySet();
		for(Entry<String,Integer> ks :mks){
			String k  = ks.getKey();
			Integer i = ks.getValue();
			System.out.println("姓名:"+k+"	 年龄:"+i);
		}
	}
}

以上

@Fzxey

原文地址:https://www.cnblogs.com/fzxey/p/10801329.html