Map集合
key 和 value 的映射
該集合存儲鍵值對。一對一對往裏存。而且要保證鍵的唯一性。
(key==null ? k==null : key.equals(k))
1,添加。
put(K key, V value)
注意返回值是V
V |
put(K key, V value)
將指定的值與此映射中的指定鍵關聯(可選操作)。 |
putAll(Map<? extends K,? extends V> m)
2,刪除。
clear()
remove(Object key)
注意返回值是V
3,判斷。
containsValue(Object value)
containsKey(Object key)
isEmpty()
4,獲取。
get(Object key)
V |
get(Object key)
返回指定鍵所映射的值;如果此映射不包含該鍵的映射關係,則返回 null 。 |
size()
values()
entrySet()
接口 Map.Entry<K,V>
-
public static interface Map.Entry<K,V>
map集合的兩種取出方式:
1,
Set<k> keySet:將map中所有的鍵存入到Set集合。因爲set具備迭代器。
所有可以迭代方式取出所有的鍵,在根據get方法。獲取每一個鍵對應的值。
Map集合的取出原理:將map集合轉成set集合。在通過迭代器取出。
//先獲取map集合的所有鍵的Set集合,keySet();
Set<String> keySet = map.keySet();
//有了Set集合。就可以獲取其迭代器。
Iterator<String> it = keySet.iterator();
while (it.hasNext())
{
String key = it.next();
//有了鍵可以通過map集合的get方法獲取其對應的值。
String value = map.get(key);
System. out .println("key:" +key+ ",value:"+value);
}
2,
Set<Map.Entry<k,v>> entrySet:將map集合中的映射關係存入到了set集合中,
而這個關係的數據類型就是:Map.Entry
Entry其實就是Map中的一個static內部接口。
爲什麼要定義在內部呢?
因爲只有有了Map集合,有了鍵值對,纔會有鍵值的映射關係。
關係屬於Map集合中的一個內部事物。
而且該事物在直接訪問Map集合中的元素
//將Map集合中的映射關係取出。存入到Set集合中。
Set<Map.Entry<String,String>> entrySet = map.entrySet();
Iterator<Map.Entry<String,String>> it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry<String,String> me = it.next();
String key = me.getKey();
String value = me.getValue();
System. out.println(key+":" +value);
}
Map
|--Hashtable:底層是哈希表數據結構,不可以存入null鍵null值。該集合是線程同步的。jdk1.0.效率低。
|--HashMap:底層是哈希表數據結構,允許使用 null 值和 null 鍵,該集合是不同步的。將hashtable替代,jdk1.2.效率高。
|--TreeMap:底層是二叉樹數據結構。線程不同步。可以用於給map集合中的鍵進行排序。和Set很像。其實大家,Set底層就是使用了Map集合
注意了,當發現有映射關係時,可以選擇map集合。
因爲map集合中存放就是映射關係
練習:
"sdfgzxcvasdfxcvdf"獲取該字符串中的字母出現的次數。
希望打印結果:a(1)c(2)....
思路:
1,將字符串轉換成字符數組。因爲要對每一個字母進行操作。
2,定義一個map集合,因爲打印結果的字母有順序,所以使用treemap集合。
3,遍歷字符數組。
將每一個字母作爲鍵去查map集合。
如果返回null,將該字母和1存入到map集合中。
如果返回不是null,說明該字母在map集合已經存在並有對應次數。
那麼就獲取該次數並進行自增。,然後將該字母和自增後的次數存入到map集合中。覆蓋調用原理鍵所對應的值。
4,將map集合中的數據變成指定的字符串形式返回
import java.util.*;
public class Ts
{
public static void main(String[]
args)
{
String s= charCount("ak+abAf1c,dCkaAbc-defa");
System. out.println(s);
}
public static String
charCount(String str)
{
char[]
chs = str.toCharArray();
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
int count
= 0;
for(int x=0;
x<chs.length; x++)
{
if(!(chs[x]>='a' &&
chs[x]<='z' || chs[x]>= 'A' &&
chs[x]<='Z'))
continue;
Integer value = tm.get(chs[x]);
if(value!=null)
count = value;
count++;
tm.put(chs[x],count); //直接往集合中存儲字符和數字,爲什麼可以,因爲自動裝箱。
count = 0;
/*
if(value==null)
{
tm.put( chs[x],1);
}
else
{
value = value + 1;
tm.put( chs[x],value);
}
*/
}
//System.out.println(tm);
StringBuilder sb = new StringBuilder();
Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Character,Integer> me = it.next();
Character ch = me.getKey();
Integer value = me.getValue();
sb.append(ch+ "("+value+")" );
}
return sb.toString();
}
}