Map集合常用方法

/*
SortedSet和TreeSet需要写一个类实现conparable,或者写一个比较器
HashMap和Hashtable需要重写HashCoed和equals方法

Map是一对一对存储的,Collection是一个一个存储的

Map集合中常用的方法
void clear() 清空map 
  boolean containsKey(Object key)  判断Map中是否包含这样的Key
  boolean containsValue(Object value) 判断Map中是否包含这样的Value
Set<Map.Entry<K,V>> entrySet() 
 
  V get(Object key)  //通过Key获取Value
  boolean isEmpty()  判断该集合是否为空
 
  Set<K> keySet() 获取Map中所有的Key 
  V put(K key, V value)  向集合中添加键值对
  V remove(Object key)   通过key将键值对删除
  Collection<V> values()   获取所有的value
 
  注意:存储在Map集合Key部分的元素需要同时重写hashCode+equals方法


*/
import java.util.*;


public class fuck13{

public static void main(String[] args){

//1.创建Map集合
//HashMap的默认初始化值是16,默认加载因子是0.75
Map persons =new HashMap();

//2.存储键值对
persons.put("10000","jack");
persons.put("13000","luck");
persons.put("10400","tom");
persons.put("10020","lucy");
persons.put("10200","kim");
persons.put("10000","lisa");

//3.判断键值对的个数
//Map中的Key是无序不可重复的,和HashCode相同
System.out.println(persons.size());//5

//4.判断集合中是否包含这样的Key
System.out.println(persons.containsKey("10000"));//true

//5.判断集合中是否包含这样的Value
//注意:Map中如果Key重复了,value采用的是覆盖
System.out.println(persons.containsValue("lisa"));//true

//6.通过Key获取Value
Object v=persons.get("10200");
System.out.println(v);

//7.通过Key删除键值对
persons.remove("10200");
System.out.println(persons.size());//4

//8.获取所有的value
Collection values=persons.values();
Iterator it=values.iterator();
while(it.hasNext()){
System.out.println(it.next());
}

//9获取所有的Key
//以下程序演示如何遍历Map集合
Set Keys=persons.keySet();
Iterator it1=Keys.iterator();
while(it1.hasNext()){
Object no=it1.next();
Object name=persons.get(no);
System.out.println(no+"-->"+name);
}

//10.entrySet
//将Map转换成Set集合
Set set=persons.entrySet();
Iterator it2=set.iterator();
while(it2.hasNext()){
System.out.println(it2.next());
}

}


}



猜你喜欢

转载自blog.csdn.net/rolic_/article/details/80315671