java集合之map

 map基本概念

Map:元素是按照键值对形式存储的。每一对元素由两部分组成。分别叫键和值
键是唯一的,值是可以重复的。
所以Map集合的底层数据结构是针对键有效,跟值无关。

map相关面试题

Map接口和Collection接口的不同?(面试题)
A:Map集合是双列集合;Map集合的键是唯一的,值是可以重复的。其实我们也可以简单的理解为Map集合的键和值是由Set和List组成;数据结构针对键有效。
B:Collection集合是单列集合;Collection集合的儿子Set是唯一的,List是可以重复的;数据结构针对元素有效。

Map集合常用方法

A:添加功能
V put(K key,V value):添加,替换或者修改。键不同,添加到集合。键相同,值替换。
B:移除功能
void clear():移除所有映射关系
V remove(Object key):根据键移除键值对元素,返回的是键对应的值
C:判断功能
boolean containsKey(Object key):判断Map集合中是否包含指定的键
boolean containsValue(Object value):判断Map集合中是否包含指定的值
boolean isEmpty():判断集合是否为空
D:获取功能
Set<Map.Entry<K,V>> entrySet():返回的是键值对对象的Set集合。
V get(Object key):根据键获取值
Set<K> keySet():所有的键的集合
Collection<V> values():所有值的集合
int size():集合的长度

public class MapDemo {
public static void main(String[] args) {
// 创建集合对象
// 创建元素
// 添加元素
// 遍历集合

// 创建集合对象
Map<String, String> map = new HashMap<String, String>();

// 添加元素
// V put(K key,V value)
// System.out.println("put:" + map.put("文章", "马伊俐"));
// System.out.println("put:" + map.put("文章", "姚笛"));
map.put("文章", "马伊俐");
map.put("谢霆锋", "张柏芝");
map.put("田亮", "叶一茜");
map.put("汪峰", "章子怡");

// void clear():移除所有映射关系
// map.clear();

// V remove(Object key):根据键移除键值对元素,返回的是键对应的值
// System.out.println("remove:" + map.remove("汪峰"));
// System.out.println("remove:" + map.remove("汪峰2"));

// boolean containsKey(Object key):判断Map集合中是否包含指定的键
// System.out.println("containsKey:" + map.containsKey("田亮"));
// System.out.println("containsKey:" + map.containsKey("森碟"));

// boolean isEmpty():判断集合是否为空
// System.out.println("isEmpty:" + map.isEmpty());

// int size():集合的长度
System.out.println("size:" + map.size());

System.out.println("map:" + map);
}
}

 map集合的遍历

1、通过获取所有的key按照key来遍历

//Set<Integer> set = map.keySet(); //得到所有key的集合
for (Integer in : map.keySet()) {
    String str = map.get(in);//得到每个key多对用value的值
}

2、通过Map.entrySet使用iterator遍历key和value

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
     Map.Entry<Integer, String> entry = it.next();
       System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}

3、通过Map.entrySet遍历key和value,推荐,尤其是容量大时

for (Map.Entry<Integer, String> entry : map.entrySet()) {
    //Map.entry<Integer,String> 映射项(键-值对)  有几个方法:用上面的名字entry
    //entry.getKey() ;entry.getValue(); entry.setValue();
    //map.entrySet()  返回此映射中包含的映射关系的 Set视图。
    System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}

4、通过Map.values()遍历所有的value,但不能遍历key

for (String v : map.values()) {
    System.out.println("value= " + v);
}
原文地址:https://www.cnblogs.com/lqhhome/p/10914467.html