07-java學習筆記-map集合

01-java學習筆記01 1.Map集合

Map集合:該集合存儲鍵值對。一對一對往裏存。
                 並且要保證 鍵的惟一性。
Map< K, V>
     1. 添加     1. put( K  key, V value)
                    2. putAll(Map<? extends K,? extends V> m)
     2. 刪除
                    1. clear()
                    2. remove(Object key)
     3. 判斷
                    1. containsKey(Object key)
                    2. containsValue(Object   value)
                    3. isEmpty()
     4. 獲取
                    1. V get(Object key)
                    2. size()
                    3.  Collection<V> values()

                    entrySet()
                    keySet()
                    
Map與Collection
Map與Collection在集合框架中屬並列存在
Map存儲的是鍵值對
Map存儲元素使用put方法,Collection使用add方法
Map集合沒有直接取出元素的方法,而是先轉成Set集合,在經過迭代獲取元素
Map集合中鍵要保證惟一性
Map集合經常使用類
Hashtable:線程安全( 同步),速度慢, 不容許存放null鍵,null值,已被HashMap替代。JDK1.0 效率低
HashMap:線程不安全( 不一樣步),速度快, 容許存放null 鍵,null值。JDK1.2 效率高
TreeMap:對鍵進行排序,排序原理與TreeSet 相同。
Map
     |--Hashtable  底層是哈希表數據結構 用做鍵的對象必須實現 hashCode方法和 equals方法
     |--HashMap  底層是哈希表數據結構
     |--TreeMap   底層是二叉樹數據結構。線程不一樣步。能夠用於給Map集合中的鍵 排序
                          和Set很像
                          其實TreeSet的底層就是TreeMap
Map共性方法
import java.util.*;
class  MapDemo
{
      public  static  void main(String[] args)
     {
          Map<String,String> map =  new HashMap<String,String>();

           // 添加元素,若是添加時出現相同的鍵,那麼後添加的值會覆蓋原有鍵對應值。
          
// 而且put方法會返回被覆蓋的值。
          System.out.println("put:"+map.put("01","zhangsan1"));
          System.out.println("put:"+map.put("01","wnagwu"));
          map.put("02","zhangsan2");
          map.put("03","zhangsan3");

          System.out.println("containsKey:"+map.containsKey("022"));
           // System.out.println("remove:"+map.remove("02"));

          System.out.println("get:"+map.get("023"));

          map.put("04", null); // 沒有意義
          System.out.println("get:"+map.get("04"));
           // 能夠經過get方法的返回值來判斷一個鍵是否存在。經過返回null來判斷。

          
// 獲取map集合中全部的值。
          Collection<String> coll = map.values();

          System.out.println(coll);
          System.out.println(map);
     }
}
map集合的兩種取出方式
    
     1.Set<E>keySet  將Map中全部的鍵存到Set集合。由於set具有迭代器。因此能夠用迭代方式取出全部的鍵。
                                再根據get方法。獲取每個鍵對應的值
     
     2.entrySet
1.keySet

          //先獲取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.entrySet

將map集合中的映射關係取出存到一個集合Set中,
這個關係就是Map.Entry類型
關係對象Map.Entry獲取到後,
就能夠經過Map.Entry中的getKey()和getValue方法獲取到key和value
Map.Entry 其實Entry也是一個接口,它是Map接口中的一個內部接口。
interface Map
{
     public static Interface Entry
     {
          public abstract Object getKey();
          public abstract Object getValue();
     }
}
class HashMap implements Map
{
     class Haha implements Map.Entry
     {
          public Object getKey();
          public Object getValue();
     }
}
練習

1.Map
     每個學生都有對應的歸屬地。
     學生Student,地址String。
     學生屬性:姓名,年齡。
     注意:姓名和年齡相同的視爲同一個學生。
     保證學生的惟一性。
          1,描述學生。
          2,定義map容器。將學生做爲鍵,地址做爲值。存入。
          3,獲取map集合中的元素。
import java.util.*;
class Student  implements Comparable<Student>
{
      private String name;
      private  int age;
     Student(String name, int age)
     {
           this.name = name;
           this.age = age;
     }
    
      public  int compareTo(Student s)
     {
           int num =  new Integer( this.age).compareTo( new Integer(s.age));
           if(num==0)
                return  this.name.compareTo(s.name);
           return num;
     }

      public  int hashCode()
     {
           return name.hashCode()+age*34;
     }
      public  boolean equals(Object obj)
     {
           if(!(obj  instanceof Student))
                throw  new ClassCastException("類型不匹配");

          Student s = (Student)obj;

           return  this.name.equals(s.name) &&  this.age==s.age;
     }
      public String getName()
     {
           return name;
     }
      public  int getAge()
     {
           return age;
     }
      public String toString()
     {
           return name+":"+age;
     }
}

class  MapTest
{
      public  static  void main(String[] args)
     {
          HashMap<Student,String> hm =  new HashMap<Student,String>();

          hm.put( new Student("lisi1",20),"beijing");
          hm.put( new Student("lisi1",20),"tianjin");
          hm.put( new Student("lisi2",22),"shanghai");
          hm.put( new Student("lisi3",24),"nanjing");
          hm.put( new Student("lisi4",25),"shenzhen");

           // 第一種取出方式 keySet

          Set<Student> keySet = hm.keySet();

          Iterator<Student> it = keySet.iterator();

           while(it.hasNext())
          {
               Student stu = it.next();
               String addr = hm.get(stu);
               System.out.println(stu+".."+addr);
          }

           // 第二種取出方式 entrySet
          Set<Map.Entry<Student,String>> entrySet = hm.entrySet();

          Iterator<Map.Entry<Student,String>> iter = entrySet.iterator();
         
           while(iter.hasNext())
          {
               Map.Entry<Student,String> me = iter.next();
               Student stu = me.getKey();
               String addr = me.getValue();
               System.out.println(stu+"....."+addr);
          }
     }
}
2. TreeMap需求:對學生對象的年齡進行升序排序。
 
由於數據是以鍵值對形式存在的。
因此要使用能夠排序的Map集合。TreeMap。

 

import java.util.*;
class StuNameComparator  implements Comparator<Student>
{
      public  int compare(Student s1,Student s2)
     {
           int num = s1.getName().compareTo(s2.getName());
           if(num==0)
                return  new Integer(s1.getAge()).compareTo( new Integer(s2.getAge()));
           return num;
     }
}

class  MapTest2
{
      public  static  void main(String[] args)
     {
          TreeMap<Student,String> tm =  new TreeMap<Student,String>( new StuNameComparator());

          tm.put( new Student("blisi3",23),"nanjing");
          tm.put( new Student("lisi1",21),"beijing");
          tm.put( new Student("alisi4",24),"wuhan");
          tm.put( new Student("lisi1",21),"tianjin");
          tm.put( new Student("lisi2",22),"shanghai");

          Set<Map.Entry<Student,String>> entrySet = tm.entrySet();

          Iterator<Map.Entry<Student,String>> it = entrySet.iterator();

           while(it.hasNext())
          {
               Map.Entry<Student,String> me = it.next();

               Student stu = me.getKey();
               String addr = me.getValue();
               System.out.println(stu+":::"+addr);
          }
     }
}
3.TreeMap練習
/*
練習:
"sdfgzxcvasdfxcvdf"獲取該字符串中的字母出現的次數。

但願打印結果:a(1)c(2).....

經過結果發現,每個字母都有對應的次數。
說明字母和次數之間都有映射關係。
注意,當發現有映射關係時,能夠選擇map集合。
由於map集合中存放就是映射關係。
何時使用map集合呢?
當數據之間存在這映射關係時,就要先想map集合。

思路:
1,將字符串轉換成字符數組。由於要對每個字母進行操做。

2,定義一個map集合,由於打印結果的字母有順序,因此使用treemap集合。

3,遍歷字符數組。
     將每個字母做爲鍵去查map集合。
     若是返回null,將該字母和1存入到map集合中。
     若是返回不是null,說明該字母在map集合已經存在並有對應次數。
     那麼就獲取該次數並進行自增。,而後將該字母和自增後的次數存入到map集合中。覆蓋調用原理鍵所對應的值。

4,將map集合中的數據變成指定的字符串形式返回。
import java.util.*;
class  MapTest3
{
      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();      } }
相關文章
相關標籤/搜索