


public class MapDemo {
public static void main(String[] args) {
Map<String, Object> map=new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", "value4");
map.put("key5", "value5");
map.put("key6", "value6");
map.put("key7", "value7");
map.put("key8", "value8");
//System.out.println(map);
//map.clear();
System.out.println(map);//清楚Map里面所有的key和value
System.out.println(map.size());//獲取Map里面有多少個鍵值對
System.out.println(map.containsKey("key8"));//true判斷Map里面是否有這么一個key
System.out.println(map.keySet());//不能直接用foreach去遍歷,否則報錯
Set<String> set=new HashSet<>(map.keySet());
for (String key : set) {
System.out.print("鍵"+key+",");
}
System.out.println(map.remove("key3"));//移出Map中指定的一個key值,value伴隨Key而生
System.out.println(map);
System.out.println(map.values());//同.keySet();一樣的功能
System.out.println(map.get("key6"));//找到key所對應的的value值,不能根據value去尋找key
//獲取Map中所有的Entry(key-value)
Set<Map.Entry<String, Object>> set1=map.entrySet();
for (Map.Entry<String, Object> entry : set1) {
String key=entry.getKey();//獲取Key
Object value=entry.getValue();//獲取Value
System.out.println(key+"<->"+value);
}
}
}


例題:
public class Char_count {
public static void main(String[] args) {
String str="esofuhwofhwourhworhiowurgiuwrgwiurgwiurfghwiuhfwsihfwiufhu";
//把字符串轉換成Char數組(字符串本來就是Char[] )
char[] arr=str.toCharArray();
//key存儲字符,value存儲字符出現的次數
Map<Character, Integer>map=new TreeMap<>();
//判斷當前字符是否在Map中的key存在
for (char ch : arr) {
if(map.containsKey(ch)){//當前Map中key包含該字符,把value取出加一再放進去
Integer old=map.get(ch);
map.put(ch, old+1);
}else{
map.put(ch, 1);//當前Map中不包含該字符,把該字符存放到Key,value值設置為1
}
}
System.out.println(map);
}
}


自然排序:

