Java基础16:map集合;

关键字:map集合;

一、集合(Map)

  1. /* 
  2. Map:该集合存储键值对。一对一往里存,而且要保证键的唯一性。 
  3.     1、添加 
  4.         put(K key,V value) 
  5.         putAll(Map<? extends K,? extends V> m) 从指定映射中将所有映射关系复制到此映射中(可选操作)。 
  6.     2、删除 
  7.         clear()   清空 
  8.         remove(Object key) 
  9.     3、判断 
  10.         containsKey(Object key)  是否包含某个key 
  11.         containsValue(Object value)  是否包含某个value 
  12.         isEmpty() 
  13.     4、获取 
  14.         get(Object key) 
  15.         int size() 返回此映射中的键-值映射关系数。  
  16.         Collection<V> values() 返回此映射中包含的值的 Collection 视图。  
  17.          
  18.         Set<Map.Entry<K,V>> entrySet() 返回此映射中包含的映射关系的 Set 视图。  
  19.         Set<K> keySet() 返回此映射中包含的键的 Set 视图。  
  20.  
  21.  
  22. Map 
  23.     |--Hashtable  
  24.         底层是哈希表数据结构,不可以存入null键null值。该集合是线程同步的 
  25.         此类实现一个哈希表,该哈希表将键映射到相应的值。任何非 null 对象都可以用作键或值。 
  26.         为了成功地在哈希表中存储和获取对象,用作键的对象必须实现 hashCode 方法和 equals 方法。 
  27.     |--HashMap 
  28.         基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。 
  29.         (除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。  
  30.     |--TreeMap 
  31.         基于红黑树(Red-Black tree)的 NavigableMap 实现。该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。  
  32. 和Set很像。 
  33. 其实大家,Set底层就是使用了Map集合。 
  34. */  
  35.   
  36.   
  37. import java.util.*;  
  38. public class Demo{    
  39.     public static void main(String[] args){    
  40.         Map<String,String> map = new HashMap<String,String>();  
  41.         //添加元素  
  42.         map.put("01","zhangsan1");  
  43.         map.put("02","zhangsan2");  
  44.         map.put("03","zhangsan3");  
  45.         map.put("null","zhangsan4");//可以存入空值,但是不常见,所以可以通过get方法的返回值,null来判断一个键的不存在  
  46.         sop(map.containsKey("02"));  
  47.         sop(map.get("02"));  
  48.         sop(map.remove("02"));  
  49.         sop(map.containsKey("02"));  
  50.         sop("-----------");  
  51.         Collection<String> coll = map.values();  
  52.         sop(coll);  
  53.           
  54.         map.put("01","zhangsan1");  //返回值是null  
  55.         map.put("01","zhangsan2");//当添加相同的键,则后添加的值会覆盖原有值,并且返回原有值  
  56.     }    
  57.     public static void sop(Object obj){  
  58.         System.out.println(obj);  
  59.     }  
  60. }   
/*
Map:该集合存储键值对。一对一往里存,而且要保证键的唯一性。
    1、添加
        put(K key,V value)
        putAll(Map<? extends K,? extends V> m) 从指定映射中将所有映射关系复制到此映射中(可选操作)。
    2、删除
        clear()   清空
        remove(Object key)
    3、判断
        containsKey(Object key)  是否包含某个key
        containsValue(Object value)  是否包含某个value
        isEmpty()
    4、获取
        get(Object key)
        int size() 返回此映射中的键-值映射关系数。 
        Collection<V> values() 返回此映射中包含的值的 Collection 视图。 
        
        Set<Map.Entry<K,V>> entrySet() 返回此映射中包含的映射关系的 Set 视图。 
        Set<K> keySet() 返回此映射中包含的键的 Set 视图。 


Map
    |--Hashtable 
        底层是哈希表数据结构,不可以存入null键null值。该集合是线程同步的
        此类实现一个哈希表,该哈希表将键映射到相应的值。任何非 null 对象都可以用作键或值。
        为了成功地在哈希表中存储和获取对象,用作键的对象必须实现 hashCode 方法和 equals 方法。
    |--HashMap
        基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。
        (除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。 
    |--TreeMap
        基于红黑树(Red-Black tree)的 NavigableMap 实现。该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。 
和Set很像。
其实大家,Set底层就是使用了Map集合。
*/


import java.util.*;
public class Demo{  
    public static void main(String[] args){  
        Map<String,String> map = new HashMap<String,String>();
        //添加元素
        map.put("01","zhangsan1");
        map.put("02","zhangsan2");
        map.put("03","zhangsan3");
        map.put("null","zhangsan4");//可以存入空值,但是不常见,所以可以通过get方法的返回值,null来判断一个键的不存在
        sop(map.containsKey("02"));
        sop(map.get("02"));
        sop(map.remove("02"));
        sop(map.containsKey("02"));
        sop("-----------");
        Collection<String> coll = map.values();
        sop(coll);
        
        map.put("01","zhangsan1");  //返回值是null
        map.put("01","zhangsan2");//当添加相同的键,则后添加的值会覆盖原有值,并且返回原有值
    }  
    public static void sop(Object obj){
        System.out.println(obj);
    }
} 


四、集合(Map-keySet)
  1. /* 
  2. 1、Set<K> keySet()  
  3.     将Map中所有的键存入到Set集合,因为set具备迭代器。 
  4.     所有可以迭代方式取出所有的键,再根据get方法,获取每一个键对应的值 
  5. */  
  6.   
  7.   
  8. import java.util.*;  
  9. public class Demo{    
  10.     public static void main(String[] args){    
  11.         Map<String,String> map = new HashMap<String,String>();  
  12.         map.put("01","zs1");  
  13.         map.put("02","zs2");  
  14.         map.put("03","zs3");  
  15.         map.put("04","zs4");  
  16.         //先获取 map 集合的所有键的 set 集合,keySet();  
  17.         Set<String> keySet = map.keySet();  
  18.         //有了Set集合,就可以获取其迭代器。  
  19.         Iterator<String> it = keySet.iterator();  
  20.         while(it.hasNext()){  
  21.             //有了键可以通过 map 集合的get方法获取其对应的值  
  22.             String key = it.next();  
  23.             sop("key:"+key+" value:"+map.get(key));  
  24.         }  
  25.           
  26.     }    
  27.     public static void sop(Object obj){  
  28.         System.out.println(obj);  
  29.     }  
  30. }   
/*
1、Set<K> keySet() 
    将Map中所有的键存入到Set集合,因为set具备迭代器。
    所有可以迭代方式取出所有的键,再根据get方法,获取每一个键对应的值
*/


import java.util.*;
public class Demo{  
    public static void main(String[] args){  
        Map<String,String> map = new HashMap<String,String>();
        map.put("01","zs1");
        map.put("02","zs2");
        map.put("03","zs3");
        map.put("04","zs4");
        //先获取 map 集合的所有键的 set 集合,keySet();
        Set<String> keySet = map.keySet();
        //有了Set集合,就可以获取其迭代器。
        Iterator<String> it = keySet.iterator();
        while(it.hasNext()){
            //有了键可以通过 map 集合的get方法获取其对应的值
            String key = it.next();
            sop("key:"+key+" value:"+map.get(key));
        }
        
    }  
    public static void sop(Object obj){
        System.out.println(obj);
    }
} 


五、集合(Map-entrySet)
  1. /* 
  2. Entry 接口方法 
  3. boolean equals(Object o) 比较指定对象与此项的相等性。  
  4.  K getKey() 返回与此项对应的键。  
  5.  V getValue() 返回与此项对应的值。  
  6.  int hashCode() 返回此映射项的哈希码值。  
  7.  V setValue(V value)  用指定的值替换与此项对应的值(可选操作)。  
  8.  
  9.  
  10. 2、Set<Map.Entry<K,V>> entrySet()  
  11.         返回此映射所包含的映射关系的 Set 视图。  
  12.         将Map集合中的映射关系存入到了set集合中,而这个关系的数据类型就是:Map.Entry 
  13.          
  14.         entrySet():将Map集合中的映射关系取出。 
  15.         这个关系就是 Map.Entry 类型 
  16.         那么关系对象 Map.Entry 获取到后,就可以通过,Map.Entry中getKey和getValue方法获取关系中的键和值 
  17. Map.Entry 其实Entry也是一个接口,她是接口中的一个内部接口。 
  18. interface Map{}{ 
  19.     public static interface Entry{ 
  20.         public abstract object getKey(); 
  21.     } 
  22. } 
  23. class HashMap implements Map{ 
  24.     class Hash implements Map.Entry{ 
  25.         public Objecgt getKey(){} 
  26.         public Objecgt getValue(){} 
  27.     } 
  28. } 
  29. */  
  30.   
  31.   
  32. import java.util.*;  
  33. public class Demo{    
  34.     public static void main(String[] args){    
  35.         Map<String,String> map = new HashMap<String,String>();  
  36.         map.put("01","zs1");  
  37.         map.put("02","zs2");  
  38.         map.put("03","zs3");  
  39.         map.put("04","zs4");  
  40.         //将Map集合中的映射关系取出。存入到Set集合中。  
  41.         Set<Map.Entry<String,String>> entrySet = map.entrySet();  
  42.         Iterator<Map.Entry<String,String>> it = entrySet.iterator();  
  43.         while(it.hasNext()){  
  44.             Map.Entry<String,String> me = it.next();  
  45.             sop("key:"+me.getKey()+" value:"+me.getValue());  
  46.         }  
  47.     }    
  48.     public static void sop(Object obj){  
  49.         System.out.println(obj);  
  50.     }  
  51. }   
/*
Entry 接口方法
boolean equals(Object o) 比较指定对象与此项的相等性。 
 K getKey() 返回与此项对应的键。 
 V getValue() 返回与此项对应的值。 
 int hashCode() 返回此映射项的哈希码值。 
 V setValue(V value)  用指定的值替换与此项对应的值(可选操作)。 


2、Set<Map.Entry<K,V>> entrySet() 
        返回此映射所包含的映射关系的 Set 视图。 
        将Map集合中的映射关系存入到了set集合中,而这个关系的数据类型就是:Map.Entry
        
        entrySet():将Map集合中的映射关系取出。
        这个关系就是 Map.Entry 类型
        那么关系对象 Map.Entry 获取到后,就可以通过,Map.Entry中getKey和getValue方法获取关系中的键和值
Map.Entry 其实Entry也是一个接口,她是接口中的一个内部接口。
interface Map{}{
    public static interface Entry{
        public abstract object getKey();
    }
}
class HashMap implements Map{
    class Hash implements Map.Entry{
        public Objecgt getKey(){}
        public Objecgt getValue(){}
    }
}
*/


import java.util.*;
public class Demo{  
    public static void main(String[] args){  
        Map<String,String> map = new HashMap<String,String>();
        map.put("01","zs1");
        map.put("02","zs2");
        map.put("03","zs3");
        map.put("04","zs4");
        //将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();
            sop("key:"+me.getKey()+" value:"+me.getValue());
        }
    }  
    public static void sop(Object obj){
        System.out.println(obj);
    }
} 


六、集合(Map练习)
  1. /* 
  2. 每一个学生都有对应的归属地 
  3. 学生Student,地址String 
  4. 学生属性:姓名,年龄 
  5. 主意:姓名和年龄相同的视为同一个学生。 
  6. 保证学生的唯一性 
  7.  
  8.  
  9. 1、描述学生 
  10. 2、定义Map容器,将学生作为键,地址作为值,存入 
  11. 3、获取map集合中元素 
  12. */  
  13. import java.util.*;  
  14. public class Demo{  
  15.     public static void main(String[] args){    
  16.         HashMap<Student,String> map = new HashMap<Student,String>();  
  17.         map.put(new Student("lisi1",21),"beijing");  
  18.         map.put(new Student("lisi2",22),"shanghai");  
  19.         map.put(new Student("lisi3",23),"nanjing");  
  20.         map.put(new Student("lisi4",24),"wuhan");  
  21.         sop("第一种");  
  22.         Set<Student> setMap = map.keySet();  
  23.         Iterator<Student> it = setMap.iterator();  
  24.         while(it.hasNext()){  
  25.             Student st = it.next();  
  26.             sop("name:"+st.getName()+" value:"+st.getAge());  
  27.         }  
  28.         sop("第二种");  
  29.         Map<Student,String> map2 = new HashMap<Student,String>();  
  30.         map2.put(new Student("lisi1",21),"beijing");  
  31.         map2.put(new Student("lisi2",22),"shanghai");  
  32.         map2.put(new Student("lisi3",23),"nanjing");  
  33.         map2.put(new Student("lisi4",24),"wuhan");  
  34.         //将Map集合中的映射关系取出。存入到Set集合中。  
  35.         Set<Map.Entry<Student,String>> entrySet = map2.entrySet();  
  36.         Iterator<Map.Entry<Student,String>> it2 = entrySet.iterator();  
  37.         while(it2.hasNext()){  
  38.             Map.Entry<Student,String> me = it2.next();  
  39.             sop("name:"+me.getKey().getName()+" value:"+me.getKey().getAge()+" address:"+me.getValue());  
  40.         }  
  41.     }    
  42.     public static void sop(Object obj){  
  43.         System.out.println(obj);  
  44.     }  
  45. }  
  46. class Student implements Comparable{  
  47.     private String name;  
  48.     private int age;  
  49.     Student(String name,int age){  
  50.         this.name = name;  
  51.         this.age = age;  
  52.     }  
  53.     public String getName(){  
  54.         return name;  
  55.     }  
  56.     public int getAge(){  
  57.         return age;  
  58.     }  
  59.     public String toString(){  
  60.         return name+":"+age;  
  61.     }  
  62.     public int hashCode(){   
  63.         return name.hashCode()+age*34;  
  64.     }  
  65.     public boolean equals(Object obj){  
  66.         if((obj instanceof Student))  
  67.             throw new ClassCastException("类型不匹配");  
  68.         Student s = (Student)obj;  
  69.         return this.name.equals(s.name)&&this.age==s.age;  
  70.     }  
  71.     public int compareTo(Object obj){  
  72.         Student s = (Student)obj;  
  73.         int num = new Integer(this.age).compareTo(new Integer(s.age));  
  74.         if(num==0)  
  75.             return this.name.compareTo(s.name);  
  76.         return num;  
  77.     }  
  78. }  
/*
每一个学生都有对应的归属地
学生Student,地址String
学生属性:姓名,年龄
主意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性


1、描述学生
2、定义Map容器,将学生作为键,地址作为值,存入
3、获取map集合中元素
*/
import java.util.*;
public class Demo{
    public static void main(String[] args){  
        HashMap<Student,String> map = new HashMap<Student,String>();
        map.put(new Student("lisi1",21),"beijing");
        map.put(new Student("lisi2",22),"shanghai");
        map.put(new Student("lisi3",23),"nanjing");
        map.put(new Student("lisi4",24),"wuhan");
        sop("第一种");
        Set<Student> setMap = map.keySet();
        Iterator<Student> it = setMap.iterator();
        while(it.hasNext()){
            Student st = it.next();
            sop("name:"+st.getName()+" value:"+st.getAge());
        }
        sop("第二种");
        Map<Student,String> map2 = new HashMap<Student,String>();
        map2.put(new Student("lisi1",21),"beijing");
        map2.put(new Student("lisi2",22),"shanghai");
        map2.put(new Student("lisi3",23),"nanjing");
        map2.put(new Student("lisi4",24),"wuhan");
        //将Map集合中的映射关系取出。存入到Set集合中。
        Set<Map.Entry<Student,String>> entrySet = map2.entrySet();
        Iterator<Map.Entry<Student,String>> it2 = entrySet.iterator();
        while(it2.hasNext()){
            Map.Entry<Student,String> me = it2.next();
            sop("name:"+me.getKey().getName()+" value:"+me.getKey().getAge()+" address:"+me.getValue());
        }
    }  
    public static void sop(Object obj){
        System.out.println(obj);
    }
}
class Student implements Comparable{
    private String name;
    private int age;
    Student(String name,int age){
        this.name = name;
        this.age = age;
    }
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;
    }
    public String toString(){
        return name+":"+age;
    }
    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 int compareTo(Object obj){
        Student s = (Student)obj;
        int num = new Integer(this.age).compareTo(new Integer(s.age));
        if(num==0)
            return this.name.compareTo(s.name);
        return num;
    }
}


七、集合(TreeMap练习)
  1. /* 
  2. 需求:对学生对象的年龄进行升序排序 
  3.  
  4.  
  5. 因为数据是以键值对形式存在的 
  6. 所以要使用可以排序的Map集合,TreeMap 
  7. */  
  8. import java.util.*;  
  9. public class Demo{  
  10.     public static void main(String[] args){    
  11.         Map<Student,String> map = new TreeMap<Student,String>();  
  12.         map.put(new Student("lisi1",23),"beijing");  
  13.         map.put(new Student("lisi2",22),"shanghai");  
  14.         map.put(new Student("lisi3",21),"nanjing");  
  15.         map.put(new Student("lisi4",24),"wuhan");  
  16.         //将Map集合中的映射关系取出。存入到Set集合中。  
  17.         Set<Map.Entry<Student,String>> entrySet = map.entrySet();  
  18.         Iterator<Map.Entry<Student,String>> it = entrySet.iterator();  
  19.         while(it.hasNext()){  
  20.             Map.Entry<Student,String> me = it.next();  
  21.             sop("name:"+me.getKey().getName()+" value:"+me.getKey().getAge()+" address:"+me.getValue());  
  22.         }  
  23.     }    
  24.     public static void sop(Object obj){  
  25.         System.out.println(obj);  
  26.     }  
  27. }  
  28. class Student implements Comparable{  
  29.     private String name;  
  30.     private int age;  
  31.     Student(String name,int age){  
  32.         this.name = name;  
  33.         this.age = age;  
  34.     }  
  35.     public String getName(){  
  36.         return name;  
  37.     }  
  38.     public int getAge(){  
  39.         return age;  
  40.     }  
  41.     public String toString(){  
  42.         return name+":"+age;  
  43.     }  
  44.     public int hashCode(){   
  45.         return name.hashCode()+age*34;  
  46.     }  
  47.     public boolean equals(Object obj){  
  48.         if((obj instanceof Student))  
  49.             throw new ClassCastException("类型不匹配");  
  50.         Student s = (Student)obj;  
  51.         return this.name.equals(s.name)&&this.age==s.age;  
  52.     }  
  53.     public int compareTo(Object obj){  
  54.         Student s = (Student)obj;  
  55.         int num = new Integer(this.age).compareTo(new Integer(s.age));  
  56.         if(num==0)  
  57.             return this.name.compareTo(s.name);  
  58.         return num;  
  59.     }  
  60. }  
/*
需求:对学生对象的年龄进行升序排序


因为数据是以键值对形式存在的
所以要使用可以排序的Map集合,TreeMap
*/
import java.util.*;
public class Demo{
    public static void main(String[] args){  
        Map<Student,String> map = new TreeMap<Student,String>();
        map.put(new Student("lisi1",23),"beijing");
        map.put(new Student("lisi2",22),"shanghai");
        map.put(new Student("lisi3",21),"nanjing");
        map.put(new Student("lisi4",24),"wuhan");
        //将Map集合中的映射关系取出。存入到Set集合中。
        Set<Map.Entry<Student,String>> entrySet = map.entrySet();
        Iterator<Map.Entry<Student,String>> it = entrySet.iterator();
        while(it.hasNext()){
            Map.Entry<Student,String> me = it.next();
            sop("name:"+me.getKey().getName()+" value:"+me.getKey().getAge()+" address:"+me.getValue());
        }
    }  
    public static void sop(Object obj){
        System.out.println(obj);
    }
}
class Student implements Comparable{
    private String name;
    private int age;
    Student(String name,int age){
        this.name = name;
        this.age = age;
    }
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;
    }
    public String toString(){
        return name+":"+age;
    }
    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 int compareTo(Object obj){
        Student s = (Student)obj;
        int num = new Integer(this.age).compareTo(new Integer(s.age));
        if(num==0)
            return this.name.compareTo(s.name);
        return num;
    }
}


八、集合(TreeMap练习-字母出现的次数)
  1. /* 
  2. 练习: 
  3. "sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数 
  4. 希望打印结果  a(1)c(2) 
  5.  
  6.  
  7. 通过结果发现,每一个字母都有对应的次数 
  8. 说明字母和次数之间都有映射关系 
  9.  
  10.  
  11. 注意了,当发现有映射关系时,可以选择map集合。 
  12. 因为map集合中存放的就是映射关系 
  13.  
  14.  
  15. 什么时候使用map集合呢? 
  16. 当数据之间存在这种映射关系时候,就要先想到map集合。 
  17.  
  18.  
  19. 思路: 
  20. 1、将字符串转换成字符数组,因为要对每一个字母进行操作 
  21. 2、定义一个map集合,因为打印结果的字母有顺序,所以使用TreeMap集合 
  22. 3、遍历字符数组, 
  23.     将每一个字母作为键去查map集合 
  24.     如果返回null,将该字母和1存入到集合中 
  25.     如果返回不是null,说明该字母在map集合已存在,并有已存在的次数,那么获取该次数并自增,然后将该字母和自增后的次数存入到map集合中,覆盖掉原键所对应的值 
  26. 4、将map集合中的数据编程指定的字符串形式返回、 
  27. */  
  28. import java.util.*;  
  29. public class Demo{  
  30.     public static void main(String[] args){    
  31.         String sb = charCount("aabfcdabcdefa");  
  32.         sop(sb);  
  33.     }    
  34.     public static String charCount(String str){  
  35.         char[] chs = str.toCharArray();  
  36.         TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();  
  37.         for(int x=0;x<chs.length;x++){  
  38.             if(!(chs[x]>='a' && chs[x]<='z'||chs[x]>='A' && chs[x]<='Z'))  
  39.                 continue;  
  40.             Integer value = tm.get(chs[x]);  
  41.             int count = 0;  
  42.             if(value!=null)  
  43.                 count = value;  
  44.             count++;  
  45.             tm.put(chs[x],count);  
  46.         }  
  47.         StringBuilder sb = new StringBuilder();  
  48.         Set<Map.Entry<Character,Integer>> entryset = new TreeSet<Map.Entry<Character,Integer>>(new myCompare());  
  49.         entryset = tm.entrySet();  
  50.         Iterator<Map.Entry<Character,Integer>> it = entryset.iterator();  
  51.         while(it.hasNext()){  
  52.             Map.Entry<Character,Integer> me = it.next();  
  53.             Character ch = me.getKey();  
  54.             Integer value = me.getValue();  
  55.             sb.append(ch+"("+value+") ");  
  56.         }  
  57.         return sb.toString();  
  58.     }  
  59.     public static void sop(Object obj){  
  60.         System.out.println(obj);  
  61.     }  
  62. }  
  63. class myCompare implements Comparator{  
  64.     public int compare(Object o1,Object o2){  
  65.     return 1;  
  66.         // o1 = (Map.Entry)o1;  
  67.         // o2 = (Map.Entry)o2;  
  68.         // int value = (Integer)(o1.getValue()).compareTo((Integer)(o2.getValue()));  
  69.         // if(value==0){  
  70.             // value = (Character)(o1.getKey()).compareTo((Character)(o2.getKey()));  
  71.         // }  
  72.     }  
  73. }  
/*
练习:
"sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数
希望打印结果  a(1)c(2)


通过结果发现,每一个字母都有对应的次数
说明字母和次数之间都有映射关系


注意了,当发现有映射关系时,可以选择map集合。
因为map集合中存放的就是映射关系


什么时候使用map集合呢?
当数据之间存在这种映射关系时候,就要先想到map集合。


思路:
1、将字符串转换成字符数组,因为要对每一个字母进行操作
2、定义一个map集合,因为打印结果的字母有顺序,所以使用TreeMap集合
3、遍历字符数组,
    将每一个字母作为键去查map集合
    如果返回null,将该字母和1存入到集合中
    如果返回不是null,说明该字母在map集合已存在,并有已存在的次数,那么获取该次数并自增,然后将该字母和自增后的次数存入到map集合中,覆盖掉原键所对应的值
4、将map集合中的数据编程指定的字符串形式返回、
*/
import java.util.*;
public class Demo{
    public static void main(String[] args){  
        String sb = charCount("aabfcdabcdefa");
        sop(sb);
    }  
    public static String charCount(String str){
        char[] chs = str.toCharArray();
        TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
        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]);
            int count = 0;
            if(value!=null)
                count = value;
            count++;
            tm.put(chs[x],count);
        }
        StringBuilder sb = new StringBuilder();
        Set<Map.Entry<Character,Integer>> entryset = new TreeSet<Map.Entry<Character,Integer>>(new myCompare());
        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();
    }
    public static void sop(Object obj){
        System.out.println(obj);
    }
}
class myCompare implements Comparator{
    public int compare(Object o1,Object o2){
    return 1;
        // o1 = (Map.Entry)o1;
        // o2 = (Map.Entry)o2;
        // int value = (Integer)(o1.getValue()).compareTo((Integer)(o2.getValue()));
        // if(value==0){
            // value = (Character)(o1.getKey()).compareTo((Character)(o2.getKey()));
        // }
    }
}


九、集合(Map扩展)
  1. /* 
  2. map扩展知识。 
  3. map结合被使用,是因为具备映射关系。 
  4.  
  5.  
  6. 一个学校,每个学校都有班级,班级都有名称 
  7.  
  8.  
  9. */  
  10. import java.util.*;  
  11. public class Demo{  
  12.     public static void main(String[] args){  
  13.         HashMap<String,String> yure = new HashMap<String,String>();  
  14.         yure.put("01","zhangsan");  
  15.         yure.put("02","lisi");          
  16.           
  17.         HashMap<String,String> jiuye = new HashMap<String,String>();  
  18.         jiuye.put("01","wangwu");  
  19.         jiuye.put("02","zhaoliu");  
  20.           
  21.         HashMap<String,HashMap<String,String>> czbk = new HashMap<String,HashMap<String,String>>();  
  22.         czbk.put("yure",yure);  
  23.         czbk.put("jiuye",jiuye);  
  24.           
  25.         //取出某个班级的学生  
  26.         //getStudentInfo(yure);  
  27.         Iterator<String> it = czbk.keySet().iterator();  
  28.         while(it.hasNext()){  
  29.             String roomName = it.next();  
  30.                         sop(roomName);  
  31.             getStudentInfo(czbk.get(roomName));  
  32.         }  
  33.     }  
  34.     public static void getStudentInfo(HashMap<String,String> roomMap){  
  35.         Iterator<String> it = roomMap.keySet().iterator();  
  36.         while(it.hasNext()){  
  37.             String id = it.next();  
  38.             String name = roomMap.get(id);  
  39.             System.out.println(id+":"+name);  
  40.         }  
  41.           
  42.     }  
  43.     public static void sop(Object obj){  
  44.         System.out.println(obj);  
  45.     }  
  46. }  
/*
map扩展知识。
map结合被使用,是因为具备映射关系。


一个学校,每个学校都有班级,班级都有名称


*/
import java.util.*;
public class Demo{
    public static void main(String[] args){
        HashMap<String,String> yure = new HashMap<String,String>();
        yure.put("01","zhangsan");
        yure.put("02","lisi");        
        
        HashMap<String,String> jiuye = new HashMap<String,String>();
        jiuye.put("01","wangwu");
        jiuye.put("02","zhaoliu");
        
        HashMap<String,HashMap<String,String>> czbk = new HashMap<String,HashMap<String,String>>();
        czbk.put("yure",yure);
        czbk.put("jiuye",jiuye);
        
        //取出某个班级的学生
        //getStudentInfo(yure);
        Iterator<String> it = czbk.keySet().iterator();
        while(it.hasNext()){
            String roomName = it.next();
                        sop(roomName);
            getStudentInfo(czbk.get(roomName));
        }
    }
    public static void getStudentInfo(HashMap<String,String> roomMap){
        Iterator<String> it = roomMap.keySet().iterator();
        while(it.hasNext()){
            String id = it.next();
            String name = roomMap.get(id);
            System.out.println(id+":"+name);
        }
        
    }
    public static void sop(Object obj){
        System.out.println(obj);
    }
}
 
  1. /* 
  2. map扩展知识。 
  3. map结合被使用,是因为具备映射关系。 
  4.  
  5.  
  6. 一个学校,每个学校都有班级,班级都有名称 
  7.  
  8.  
  9. */  
  10. import java.util.*;  
  11. public class Demo{  
  12.     public static void main(String[] args){  
  13.         HashMap<String,String> yure = new HashMap<String,String>();  
  14.         yure.put("01","zhangsan");  
  15.         yure.put("02","lisi");          
  16.           
  17.         HashMap<String,String> jiuye = new HashMap<String,String>();  
  18.         jiuye.put("01","wangwu");  
  19.         jiuye.put("02","zhaoliu");  
  20.           
  21.         HashMap<String,HashMap<String,String>> czbk = new HashMap<String,HashMap<String,String>>();  
  22.         czbk.put("yure",yure);  
  23.         czbk.put("jiuye",jiuye);  
  24.           
  25.         //取出某个班级的学生  
  26.         //getStudentInfo(yure);  
  27.         Iterator<String> it = czbk.keySet().iterator();  
  28.         while(it.hasNext()){  
  29.             String roomName = it.next();  
  30.                         sop(roomName);  
  31.             getStudentInfo(czbk.get(roomName));  
  32.         }  
  33.     }  
  34.     public static void demo2(){  
  35.         HashMap<String,List<String>> czbk = new HashMap<String,List<String>>();  
  36.         List yure = new ArrayList<Student>();  
  37.         List jiuye = new ArrayList<Student>();  
  38.           
  39.         yure.add(new Student("01","zhangsan"););  
  40.         yure.add(new Student("02","lisi"););  
  41.         jiuye.add(new Student("01","wangwu"););  
  42.         jiuye.add(new Student("02","zhaoliu"););  
  43.     }  
  44.     public static void getInfos(){  
  45.           
  46.     }  
  47.     public static void getStudentInfo(HashMap<String,String> roomMap){  
  48.         Iterator<String> it = roomMap.keySet().iterator();  
  49.         while(it.hasNext()){  
  50.             String id = it.next();  
  51.             String name = roomMap.get(id);  
  52.             System.out.println(id+":"+name);  
  53.         }  
  54.           
  55.     }  
  56.     public static void sop(Object obj){  
  57.         System.out.println(obj);  
  58.     }  
  59. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值