Map集合及使用

  1. Map集合及使用  
  2.    
  3. / *  
  4. Map集合:该集合存储键值对。一对一对往里存。而且要保证键的唯一性。  
  5.    
  6. 1,添加。  
  7.     V put(K key,V value); 返回该键对应的原有的值,操作完新值覆盖旧值。  
  8.    putAll(Map<? extends K,? extends V> m)  
  9. 2,删除。  
  10.    clear();  
  11.    remove(Object key);  
  12. 3,判断。  
  13.    boolean containsKey(Object key);  
  14.    boolean containsValue(Object Value);  
  15.    boolean isEmpty();  
  16. 4,获取。  
  17.    V get(Object key);  
  18.    size();  
  19.    values();  
  20.    
  21. ***Map集合的两种取出方式:  
  22. entrySet();  
  23. keySet();   
  24.   
  25. Map |--HashTable: 底层是哈希表结构,不可以存入nullnull值,是线程同步的。效率低  
  26.        |--HashMap: 底层是哈希表结构,允许使用nullnull值,是线程不同步的。效率高  
  27.        |--TreeMap: 底层是二叉树数据结构,可以用于给Map集合中元素排序线程不同步。  
  28. 和Set很像,实际上,Set底层就是使用了Map集合。  
  29.    
  30. Map集合的两种取出方式:  
  31. 1.Set<k> keySet = map.keySet();将Map中所有的键存入到Set集合。  
  32.   由于Set具备迭代器,用迭代方式取出所有键,再由get方法,获取每一个键对应的值。  
  33.    
  34.   原理:将Map集合转成Set集合,元素为键,再通过迭代器取出值。  
  35.    
  36. 2.Set< Map.Entry<k,v> > entrySet:  
  37.   将Map集合中的映射关系存入Set集合中,这个关系的数据类型为Map.Entry。  
  38.    
  39. 【注意】:  
  40. public static interface Map.Entry<K,V>映射项(键-值对)。  
  41. Map.entrySet 方法返回映射的collection 视图,其中的元素属于此类。获得映射项引用的唯一  
  42. 方法是通过此 collection 视图的迭代器来实现。这些Map.Entry 对象仅 在迭代期间有效;更确切地讲,如果在迭代器返回项之后修改了底层映射,则某些映射项的行为是不确定的,除了通过 setValue 在映射项上执行操作之外。  
  43.   
  44. 【Map.Entry】  
  45. 其实Entry也是一个接口,它是Map接口中的一个内部接口。  
  46. interface Map  
  47. {  
  48.        public static interface Entry{//对外提供,影射关系  
  49.               public abstract Object getKey();  
  50.               public abstract Object getValue  
  51.        }  
  52. }  
  53. class HashMap implements Map.Entry  
  54. {  
  55.        class Inner implements Map.Entry  
  56.        {  
  57.               public Object getKey(){}  
  58.               public Object getValue(){}  
  59.        }  
  60. }  
  61. */  
  62. /* 
  63. import java.util.*; 
  64. class  MapDemo 
  65. { 
  66.        public static void main(String[] args) 
  67.        { 
  68.               Map<String, String> map = new HashMap<String, String>(); 
  69.               //添加元素 
  70.               map.put("01","jack1"); 
  71.               map.put("02","jack2"); 
  72.               map.put("03","jack3"); 
  73.               System.out.println("put:"+map.put("04","jack4")); 
  74.               System.out.println("put:"+map.put("04","jack5"));//jack5被覆盖 
  75.                            
  76.               ①基本操作 
  77.               System.out.println("containKey:"+map.containsKey("02")); 
  78.               System.out.println("remove:"+map.remove("02")); 
  79.   
  80.               System.out.println("get:"+ map.get("03")); 
  81.               //可以通过get方法的返回值来判断一个键是否存在,通过返回null来判断 
  82.   
  83.               //获取Map集合中所有的值。 
  84.               Collection<String> coll = map.values(); 
  85.               System.out.println(coll); 
  86.               System.out.println(map); 
  87.               
  88.               ②第一种取出方法: 
  89.               //先获取map集合的所有键的Set集合,使用keySet(); 
  90.               Set<String> keySet = map.keySet(); 
  91.   
  92.               //有了Set集合,就可以获取其迭代器。 
  93.               Iterator<String> it = keySet.iterator(); 
  94.               while (it.hasNext()) 
  95.               { 
  96.                      String key = it.next(); 
  97.                      //有了键就可以通过Map集合的get方法获取对应的值 
  98.                      System.out.println("key :"+key+"..."+"value :"+map.get(key)); 
  99.               } 
  100.         ③第二种取出方法: 
  101.               //讲Map集合中的映射关系取出,存入到Set集合中。 
  102.               Set<Map.Entry<String,String>> entrySet = map.entrySet(); 
  103.               Iterator<Map.Entry<String,String>> it = entrySet.iterator(); 
  104.   
  105.               while (it.hasNext()) 
  106.               { 
  107.                      Map.Entry<String,String> me = it.next(); 
  108.                      String key = me.getKey(); 
  109.                      String value = me.getValue(); 
  110.                      System.out.println("key:"+key+"..."+"value:"+value); 
  111.               } 
  112.               
  113.        } 
  114. } 
  115. */  
  116. /* 
  117.  
  118. 【练习一】: 
  119. 每一个学生都有对应的归属地。学生Student,地址String。 
  120. 学生属性:姓名和年龄。姓名和年龄相同视为同一个学生、 
  121. 需要保证学生的唯一性。 
  122. 【练习二】:接【练习一】对学生对象的年龄进行升序排序 
  123. * / 
  124. import java.util.*; 
  125. class Student implements Comparable<Student> 
  126. { 
  127.        private String name; 
  128.        private int age; 
  129.        Student(String name, int age){ 
  130.               this.name = name; 
  131.               this.age = age; 
  132.        } 
  133.        public String getName(){ 
  134.               return name; 
  135.        } 
  136.        public int getAge(){ 
  137.               return age; 
  138.        } 
  139.        public String toString(){ 
  140.               return name+" : "+age; 
  141.        } 
  142.        //Map的put操作,会调用containsKey(使用equals)判断,因此需要覆盖hashCode和equals方法。 
  143.        public int hashCode(){ 
  144.               System.out.println("check1"); 
  145.               return this.age*21+this.name.hashCode(); 
  146.        } 
  147.        public boolean equals(Object obj){ 
  148.               if(!(obj instanceof Student))//犯错笔记:记得加!符 
  149.                      throw new ClassCastException("Not a student type"); 
  150.               System.out.println("check2"); 
  151.               Student p = (Student)obj; 
  152.               return this.name.equals(p.name)&&this.age == p.age; 
  153.        } 
  154.        //为了防止Student被装入TreeSet集合时进行排序,需要实现Comparable接口和复写compareTo 
  155.        public int compareTo(Student stu){ 
  156.               int num = new Integer(this.age).compareTo(new Integer(stu.age)); 
  157.               if(num == 0) 
  158.                      return this.name.compareTo(stu.name); 
  159.               return num; 
  160.        } 
  161. } 
  162. class Comp implements Comparator<Student>//可以利用已经实现Comparable的功能,也可以利用比较器 
  163. { 
  164.        public int compare(Student s1,Student s2){ 
  165.               int num = new Integer(s1.getAge()).compareTo(new Integer(s2.getAge())); 
  166.               if(num == 0) 
  167.                      return s1.getName().compareTo(s2.getName()); 
  168.               return num; 
  169.        } 
  170. } 
  171. class MapDemo 
  172. { 
  173.        public static void main(String[] args) 
  174.        { 
  175.               //Map<Student,String> map = new HashMap<Student,String>(); 
  176.               //TreeMap元素需要排序,因此需要定义比较器。 
  177.               Map<Student,String> map = new TreeMap<Student,String>(new Comp());     
  178.               
  179.               map.put(new Student("Emma",22),"Nanjing"); 
  180.               map.put(new Student("Mike",25),"Beijing"); 
  181.               map.put(new Student("Jack",20),"Haikou"); 
  182.               map.put(new Student("Penny",27),"Wuhan"); 
  183.               //map.put(new Student("Penny",27),"Wuhan"); 
  184.               map.put(new Student("Lily",27),"Hankou");//覆盖掉上一个Penny 
  185.         
  186.               Set<Map.Entry<Student,String>> entryset =  map.entrySet(); 
  187.               Iterator<Map.Entry<Student,String>> it = entryset.iterator(); 
  188.               while (it.hasNext()) 
  189.               { 
  190.                      Map.Entry<Student,String> me =it.next(); 
  191.                      Student key = me.getKey(); 
  192.                      String value = me.getValue(); 
  193.                      //System.out.println("Student:"+key.getName()+""+key.getAge()+"...."+"City :"+value); 
  194.                      System.out.println(key+"..."+value); 
  195.               } 
  196.        } 
  197. } 
  198. /* 
  199.  
  200. Map扩展知识: 
  201.   
  202. Map集合被使用是因为具备映射关系。 
  203. 双层映射: 
  204. (一对一+一对一) 
  205. HashMap<String,HashMap<String,String>>h=new HashMap<String,HashMap<String,String>>(); 
  206. (一对多) 
  207. HashMap<String,List<Student>> h = new HashMap<String,List<Student>>();*//* 
  208.  
  209. 【需求】:"sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数。 
  210. 打印格式:a(1)c(2)... 
  211.   
  212. 通过结果发现,字母的次数之间有映射关系。可以使用Map集合。 
  213. */  
  214. import java.util.*;  
  215. class Comp implements Comparator<Character>  
  216. {  
  217.        public int compare(Character ch1,Character ch2){  
  218.               return (new Integer(ch1)).compareTo(new Integer(ch2));  
  219.    
  220.        }  
  221. }  
  222. class MapTest  
  223. {  
  224.        public static void main(String[] args)  
  225.        {             
  226.               StringBuilder sb = new StringBuilder("s,dfg,zxcvasd,fxcvdf");  
  227.                
  228.               show(sb);  
  229.        }  
  230.    
  231.        public static void show(StringBuilder sb){  
  232.                
  233.               Map<Character,Integer> map = new TreeMap<Character,Integer>(new Comp());  
  234.    
  235.               for (int index=0; index<sb.length() ;index++ )  
  236.               {  
  237.                       
  238.                      char ch = sb.charAt(index);  
  239.                      //System.out.println(ch);  
  240.                      if ((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))//犯错笔记:记住需要统计的只是字母个数。  
  241.                      {  
  242.                             if(map.containsKey(ch)){                            
  243.                                    int value = map.get(ch);  
  244.                                    map.put(ch,++value);  
  245.                             }else{  
  246.                                    map.put(ch,1);  
  247.                             }  
  248.                      }      
  249.               }  
  250.               Set<Character> s = map.keySet();  
  251.    
  252.               Iterator<Character> it = s.iterator();  
  253.               while (it.hasNext())  
  254.               {  
  255.                      char cha = it.next();  
  256.                      System.out.print(cha+"("+map.get(cha)+")"+" ");  
  257.               }  
  258.               System.out.println("\n");  
  259.                
  260.        }  
  261. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值