JavaSE-day18-集合-Map

1.Map 的特点和常用方法

Map:一次添加一对元素。Collection 一次添加一个元素。
    Map也称为双列集合,Collection集合称为单列集合。
    其实map集合中存储的就是键值对。 
    map集合中必须保证键的唯一性。 
    
    
常用方法:
1,添加。
    value put(key,value):返回前一个和key关联的值,如果没有返回null.

2,删除。
    void  clear():清空map集合。
    value remove(key):根据指定的key翻出这个键值对。 

3,判断。
    boolean containsKey(key):
    boolean containsValue(value):
    boolean isEmpty();

4,获取。 
    value get(key):通过键获取值,如果没有该键返回null。
                    当然可以通过返回null,来判断是否包含指定键。 
    int size(): 获取键值对的个数。 
    
                        
    
Map常用的子类:
    |--Hashtable :内部结构是哈希表,是同步的。不允许null作为键,不允许null作为值。
        |--Properties:用来存储键值对型的配置文件的信息,可以和IO技术相结合。         
    |--HashMap : 内部结构是哈希表,不是同步的。允许null作为键,null作为值。
    |--TreeMap : 内部结构是二叉树,不是同步的。可以对Map集合中的键进行排序。 

    
    

 

2.常用方法演示

package day19;
import java.util.*;
public class MapDemo {
    public static void main(String[] args) {
        test1();
    }
    //知识点1:键值相同会覆盖前面一个元素;
    public   static  void  test1(){
        Map<Integer ,String >  map= new HashMap<Integer,String >();
        //1.添加元素
        System.out.println( map.put(2,"qqqq"));
        System.out.println( map.put(4,"qqqq"));
        System.out.println( map.put(7,"aaa"));
        System.out.println(map.put(7,"bbb"));//替代 key 值为7 的值
        System.out.println(map);//{7=bbb}
        //2.删除元素
        System.out.println(map.remove(7));//返回删除元素的值bbb
        System.out.println(map);//{}
        //3.获取元素
        System.out.println("get ="+map.get(2));//传入key
        //4. 遍历   Map 没有迭代器 跟Colletion 没啥关系。
        //keySet 返回包含[键的Set视图]。  public Set<K>  keySet()
        //Map-----keySet()----Set(key)  ---- iterator---map.get()
        Set<Integer> set = map.keySet();
        Iterator it=  set.iterator();
        while(it.hasNext()){
        Integer  key=  (Integer) it.next();
        System.out.println(map.get(key));

        }
        //  5. entrySt() 返回包含映射关系的Set视图
        //Set<Map.Entry<K,V>> entrySet()
        // Map ---键和值封装成一个对象--enterSet-- -Set<Map.Entry<key,value>>--
        System.out.println(" entrySey()");

        Set<Map.Entry<Integer,String >> mapSet =map.entrySet();
     Iterator<Map.Entry<Integer,String >>   iterator=mapSet.iterator();
     while(iterator.hasNext()){
          Map.Entry<Integer ,String >  me=iterator.next();
          Integer  key= me.getKey();
          String   value=me.getValue();
         System.out.println(" key ="+key+" value "+value);
       //  6.Collection<V> values()
       //返回此地图中包含的值的Collection视图。
        System.out.println("Collection ");
         Collection<String >   collection =map.values();
        Iterator  iterator1 =collection.iterator();
        while(iterator1.hasNext()){
          System.out.println(iterator1.next());
        }
     }
    }
}

3.重点方法keySet

4.重点方法entrySet

5.重点方法values

6.常见子类对象

7.HashMap存储自定义对象

package day19;

import day18.TreePerson;

public class Student   {
 String   name;
 int    age;

 Student(String name,int age){
     this.age=age;
     this.name=name;
 }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
    
    @Override
    public String toString() {
        return   this.name+" --"+this.age ;
    }
}
public  static  void test2(){

    HashMap<Student,String > hashMap =new HashMap<Student,String>();
    hashMap.put(new Student("aaaa",29),"北京");
    hashMap.put(new Student ("bbbb",24),"上海");
    hashMap.put(new Student("cccc",23),"沈阳");
    Set<Student>  students=hashMap.keySet();
    Iterator  iterator =students.iterator();
    while(iterator.hasNext()){
        Student  student =(Student) iterator.next();
     System.out.println(" name :"+student.name+"age :"+student.age);

    }
}

 

 

8.Tree存储自定义对象

package day19;

import day18.TreePerson;

public class Student   implements  Comparable {
 String   name;
 int    age;

 Student(String name,int age){
     this.age=age;
     this.name=name;
 }
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    @Override
    public int compareTo(Object o) {

     Student   student =(Student )o;
        int temp=this.age-student.age;
        System.out.println(" temp="+temp);
        System.out.println(" 当前对象"+this +" 传入对象"+student);
        return temp; //第一种
    }
    @Override
    public String toString() {
        return   this.name+" --"+this.age ;
    }
}
public static  void  test3(){
    
    TreeMap<Student,String >  tm =new TreeMap<Student,String>();
    tm.put(new Student("aaaa",29),"北京");
    tm.put(new Student ("bbbb",24),"上海");
    tm.put(new Student("cccc",23),"沈阳");
    Set<Student>  students=tm.keySet();
    Iterator  iterator =students.iterator();
    while(iterator.hasNext()){
        Student  student =(Student) iterator.next();
        System.out.println(" name :"+student.name+"age :"+student.age);
    }
}

HashMap  LinkedHashMap  遍历

Iterator <Map.Entry<Integer,String >> iterator = hm.entrySet().iterator();

public class MapTest {
    public static void main(String[] args){
      //  test();
      // stringCount("abcdab");
     //   stringCount("a");
       stringCount(null);
        stringCount("a");
        stringCount("   ");
       stringCount("AAAbbbbccccccdddddAAAaaa");
    }
    public  static void  test(){
       HashMap<Integer,String>   hm= new LinkedHashMap<Integer, String>();//key=7  value aaaa key=5  value bbbb key=2  value cccc key=4  value dddd
      //  HashMap<Integer,String>   hm= new HashMap<Integer, String>();// key=2  value cccc key=4  value dddd key=5  value bbbb key=7  value aaaa
        hm.put(7,"aaaa");
        hm.put(5,"bbbb");
        hm.put(2,"cccc");
        hm.put(4,"dddd");
      Iterator <Map.Entry<Integer,String >>  iterator  = hm.entrySet().iterator();
      while(iterator.hasNext()){
          Map.Entry<Integer ,String > map= iterator.next();
          System.out.print (" key=" +map.getKey()+"  value "+map.getValue());
      }
    }

练习: 统计字符串中各个字符出现次数

public class MapTest {
    public static void main(String[] args){
      //  test();
      // stringCount("abcdab");
     //   stringCount("a");
       stringCount(null);
        stringCount("a");
        stringCount("   ");
       stringCount("AAAbbbbccccccdddddAAAaaa");
    }

    //记录字母出现次数
    public  static   void  stringCount(String   str){
        HashMap<Character ,Integer>  map =new HashMap<Character, Integer>();//保存各个字符 次数
        if(str==null){
            System.out.println(" str  ==null ");
            return;
        }
        int  index=0;
        while (str.length()>0){// map.containsKey 判断是否存在这个键   统计完 substring 获取下一个子串  
          Character   ch =str.charAt(0);
          if( map.containsKey(ch)){
             int  times=map.get(ch) ;
             map.put(ch,times+1);
          }else{
              map.put(ch,1);
          }
            int  length=str.length();
        //     System.out.println("length="+length);
            if(str.length()>0){
                str=str.substring(1);
            }
        }
        Iterator<Map.Entry<Character,Integer>>  iterator =map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Character ,Integer>   me=  iterator.next();
            System.out.println(" key ="+me.getKey()+" value ="+me.getValue());
        }
      System.out.println(" --------------------");
    }
}

输出结果: str  ==null 
 key =a value =1
 --------------------
 key =  value =3
 --------------------
 key =A value =6
 key =a value =3
 key =b value =4
 key =c value =6
 key =d value =5
 --------------------

思路: 字母和次数存在的映关系,TreeMap 可以保证唯一具备顺序a b,c,....

1. 因为操作的是字符,所以先将字符串转换为字符数组。

2.遍历字符数组,每一个字母比对Map  。

3.如果键值存在   times+1 存入,如果不存在则存入这个(key,1 );

4.排除不是字母的字符

  char  ch=chractor[index];
           if(!(ch>='A'&&( ch<='Z')||(ch >='a'&&ch <='z')  )){
             continue;
            }

 public  static   void  stringCountByArray(String   str){
        HashMap<Character ,Integer>  map =new HashMap<Character, Integer>();
        if(str==null){
            System.out.println(" str  ==null ");
            return;
        }
        char[] chractor=  new  char[str.length()];
        str.getChars(0,str.length(),chractor,0);//转为数组

     for (int  index=0;index<chractor.length;index++){
             char  ch=chractor[index];
           if(!(ch>='A'&&( ch<='Z')||(ch >='a'&&ch <='z')  )){
             continue;
            }
            if( map.containsKey(chractor[index])){
                int  times=map.get(chractor[index]) ;
                map.put(chractor[index],times+1);
            }else{
                map.put(chractor[index],1);
            }
        }
        Iterator<Map.Entry<Character,Integer>>  iterator =map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Character ,Integer>   me=  iterator.next();
            System.out.println(" key ="+me.getKey()+" value ="+me.getValue());
        }
        System.out.println(" --------------------");
    }
 //  TreeMap实现
 public  static   void  stringCountByTreeMap(String   str){
        TreeMap<Character ,Integer> map =new TreeMap<Character, Integer>();
        if(str==null){
            System.out.println(" str  ==null ");
            return;
        }
        char[] chractor=  str.toCharArray();
        //str.getChars(0,str.length(),chractor,0);//转为数组

        for (int  index=0;index<chractor.length;index++){
          char  ch=chractor[index];
         if(!(ch>='A'&&( ch<='Z')||(ch >='a'&&ch <='z')  )){
             continue;
         }//排除不是字母
            if( map.containsKey(chractor[index])){
                int  times=map.get(chractor[index]) ;
                map.put(chractor[index],times+1);
            }else{
                map.put(chractor[index],1);
            }
        }
        Iterator<Map.Entry<Character,Integer>>  iterator =map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Character ,Integer>   me=  iterator.next();
            System.out.println(" key ="+me.getKey()+" value ="+me.getValue());
        }
        System.out.println(" --------------------");
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值