关于Map集合
Map集合与Collection集合有着较大区别,Map集合与Collection集合同属于java.util包。与Collection集合中的List集合和Set集合中一个元素由一个数据构成不同,Map集合一个元素是由两个数据构成的。
特点:
- Map集合中的两个数据是键(key)与值(value),形式是key:value.
- Map集合中的值(value)可以重复,但是键(key)不可以重复,每个键只能对应一个值
Map集合常用方法
- V put(L key,V value):假若集合中已有key,则修改key对应的value,若没有,则创建一个key:value
- void clear():清除所有元素
- V remove(Object key):清除指定键的元素
- boolean containsKey(Object key):判断集合中是否含有指定的键
- boolean containsValue(Object value):判断集合中是否含有指定的值
- boolean isEmpty():判断集合是否为空
- Set<Map.Entry<K,V>> entrySet():遍历
- V get(Object key):根据指定的键获取值
- Set < K > keySet():获取集合中所有键的集合
- Collection values():获取集合中所有值的集合
- int size():返回集合中键值对的个数
基本使用
import java.sql.SQLOutput;
import java.util.*;
public class Construct {
Map<String,String> map = new HashMap<String,String>();
private void Construction(){
map.put("张三","1");
map.put("李四","2");
map.put("王五","3");
map.put("赵六","4");
}
public void IsContainsKey(){
Construction();
System.out.println("是否存在张三");
System.out.println(map.containsKey("张三"));
}
public void IsContainsValue(){
Construction();
System.out.println("是否存在值4");
System.out.println(map.containsValue("4"));
}
public void IsEmpty(){
Construction();
System.out.println("集合是否为空");
System.out.println(map.isEmpty());
}
public void SizeOf(){
Construction();
System.out.println("获取键值对的对数");
System.out.println(map.size());
}
public void SetCollection1(){
Construction();
Set<String> set1 = map.keySet();
System.out.println("获取key集合Set<T>");
for(String key:set1){
System.out.println(map.get(key));
}
}
public void SetCollection2(){
Construction();
Set<String> set1 = map.keySet();
System.out.println("获取value的Collection<T>");
Collection <String> value = map.values();
for(String s:set1){
System.out.println(map.get(value));
}
}
public void EntrySetTest(){
Set<Map.Entry<String,String>> entrySet = map.entrySet();
for(Map.Entry<String,String> entry:entrySet){
System.out.println(entry.getKey()+":"+ entry.getValue());
}
}
public void RemoveTest(){
Construction();
map.remove("张三");
System.out.println(map);
}
public void ClearTest(){
Construction();
map.clear();
System.out.println(map);
}
}
public class Test {
public static void main(String []args){
Construct list1 = new Construct();
list1.ClearTest();
list1.EntrySetTest();
list1.IsContainsKey();
list1.IsContainsValue();
list1.RemoveTest();
list1.IsEmpty();
list1.SetCollection1();
list1.SetCollection2();
list1.SizeOf();
}
}
123 — Postimages (postimg.cc)
1243 — Postimages (postimg.cc)