Article / 文章中心

Map

发布时间:2021-11-18 点击数:398

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(): 获取键值对的个数。


例:


        public static void main(String[] args) {

                 Map<Integer,String> map = new HashMap<Integer,String>();


method(map);


                 method_2(map);


        }


        public static void method_2(Map<Integer,String> map){

             


                 map.put(8,"zhaoliu");


                 map.put(2,"zhaoliu");


                 map.put(7,"xiaoqiang");


                 map.put(6,"wangcai");


                 Collection<String> values = map.values();


                 Iterator<String> it2 = values.iterator();


                 while(it2.hasNext()){

                         System.out.println(it2.next());


                 }


                 /*


                  * 第一种遍历Map集合


                  * 通过Map转成set就可以迭代。


                  * 找到了另一个方法。entrySet。


                  * 该方法将键和值的映射关系作为对象存储到了Set集合中,而这个映射关系的类型就是Map.Entry类型(结婚证)


                  */


                 Set<Map.Entry<Integer, String>> entrySet = map.entrySet();


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


                 while(it.hasNext()){

                         Map.Entry<Integer, String> me = it.next();


                         Integer key = me.getKey();


                         String value = me.getValue();


                         System.out.println(key+"::::"+value);


                 }


                 //第二种遍历Map集合的方法


                 //取出map中的所有元素。


                 //原理,通过keySet方法获取map中所有的键所在的Set集合,在通过Set的迭代器获取到每一个键,


                 //在对每一个键通过map集合的get方法获取其对应的值即可。


                 Set<Integer> keySet = map.keySet();


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


                 while(it.hasNext()){

                         Integer key = it.next();


                         String value = map.get(key);


                         System.out.println(key+":"+value);


                 }


        }


public static void method(Map<Integer,String> map){//学号和姓名


                 // 添加元素。


                 System.out.println(map.put(8, "wangcai"));//null


                 System.out.println(map.put(8, "xiaoqiang"));//wangcai 存相同键,值会覆盖。


                 map.put(2,"zhangsan");


                 map.put(7,"zhaoliu");


                 //删除。


                 System.out.println("remove:"+map.remove(2));


                 //判断。


                 System.out.println("containskey:"+map.containsKey(7));


                 //获取。


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


                 System.out.println(map);


                 Outer.Inner.show();


        }


Map常用的子类:


        |--Hashtable :内部结构是哈希表,是同步的。不允许null作为键,null作为值。


                 |--Properties:用来存储键值对型的配置文件的信息,可以和IO技术相结合。


        |--HashMap : 内部结构是哈希表,不是同步的。允许null作为键,null作为值。


        |--TreeMap : 内部结构是二叉树,不是同步的。可以对Map集合中的键进行排序。


例1、:HashMap应用举例:


public  class Person {

        public int hashCode() {

                 final int prime = 31;


                 int result = 1;


                 result = prime * result + age;


                 result = prime * result + ((name == null) ? 0 : name.hashCode());


                 return result;


        }



注:举例中的Person对象有存在重复的,但是Person如果没有实现hashCode()和equals(Object obj)这两个方法,就无法比较出对象的hash值相等,所以会在结果中看到两个相同的结果,如果实现这两个方法就可以比较对象是否相等,如果相等则覆盖原来的对象的值。实现这两个对象的方法:Source->Generate hashCode() and equals() 然后在选择要比较的属性


        public boolean equals(Object obj) {


                 if (this == obj)


                         return true;


                 if (obj == null)


                         return false;


                 if (getClass() != obj.getClass())


                         return false;


                 Person other = (Person) obj;


                 if (age != other.age)


                         return false;


                 if (name == null) {

                         if (other.name != null)


                                  return false;


                 } else if (!name.equals(other.name))


                         return false;


                 return true;


        }


        private String name;


        private int age;


        public Person() {

                 super();


             


        }


        public  String  getName() {

                 return name;


        }


        public int getAge() {

                 return age;


        }


        public Person(String name, int age) {

                 super();


                 this.name = name;


                 this.age = age;


        }


}



import java.util.HashMap;


import java.util.Iterator;



public class ThreadDemo {

        public static void main(String[] args) {

                 HashMap<Person, String> hMap = new HashMap<Person, String>();


                 hMap.put(new Person("lisi", 23), "北京");


                 hMap.put(new Person("zhaolliu", 45), "上海");


                 hMap.put(new Person("xiaoqiang", 56), "北京");


                 hMap.put(new Person("wangcai", 21), "大连");


                 hMap.put(new Person("lisi", 23), "北京");


                 Iterator<Person> it = hMap.keySet().iterator();


                 while (it.hasNext()) {

                         Person key = it.next();


                         String value = hMap.get(key);


                         System.out.println(key.getName() + ":" + key.getAge() + "---"


                                           + value);


                 }


        }


}


例2、TreeMap使用。


package aaa;


public  class Person {


        private String name;


        private int age;


        public Person() {


                 super();


        }


        public  String  getName() {


                 return name;


        }


        public int getAge() {


                 return age;


        }


        public Person(String name, int age) {


                 super();


                 this.name = name;


                 this.age = age;


        }


}


package aaa;


public class Student extends Person {


        public Student() {


                 super();


        }


        public Student(String name, int age) {


                 super(name, age);


        }


}


package aaa;


import java.util.TreeMap;


import java.util.Iterator;


public class ThreadDemo {


        public static void main(String[] args) {


                 TreeMap<Student, String> hMap = new TreeMap<Student, String>(new ComparetorByName());


                 hMap.put(new Student("lisi", 23), "北京");


                 hMap.put(new Student("zhaolliu", 45), "上海");


                 hMap.put(new Student("xiaoqiang", 56), "北京");


                 hMap.put(new Student("wangcai", 21), "大连");


                 hMap.put(new Student("lisi", 23), "东京");


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


                 while (it.hasNext()) {


                         Person key = it.next();


                         String value = hMap.get(key);


                         System.out.println(key.getName() + ":" + key.getAge() + "---"


                                           + value);



输出结果:


lisi:23---东京


wangcai:21---大连


xiaoqiang:56---北京


zhaolliu:45---上海



                 }



        }


}






例3、LinkedHashMap使用举例


import java.util.Iterator;


import java.util.LinkedHashMap;


import java.util.Map;


import java.util.Set;


public class ThreadDemo {



        public static void main(String[] args) {


        LinkedHashMap<Integer, String> linkedHashMap=new LinkedHashMap<>();


        linkedHashMap.put(2, "sd");


        linkedHashMap.put(3, "qwdsa");


        linkedHashMap.put(1, "dfsd");


        linkedHashMap.put(9, "sewq");


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


        while (iterator.hasNext()) {


                 Map.Entry<Integer, String> mEntry=iterator.next();


                 Integer keyInteger=mEntry.getKey();


                 String valueString=mEntry.getValue();


                                  System.out.println(keyInteger+":"+valueString);



输出结果:


2:sd


3:qwdsa


1:dfsd


9:sewq


结果是有序的


        }



        }


}







练习:"fdgavcbsacdfs" 获取该字符串中,每一个字母出现的次数。


package aaa;


import java.util.Iterator;


import java.util.Map;


import java.util.TreeMap;


/*


* 练习:


* "fdgavcbsacdfs" 获取该字符串中,每一个字母出现的次数。


* 要求打印结果是:a(2)b(1)...;


* 思路:


* 对于结果的分析发现,字母和次数之间存在着映射的关系。而且这种关系很多。


* 很多就需要存储,能存储映射关系的容器有数组和Map集合。


* 关系一方式有序编号吗?没有!


* 那就是使用Map集合。 又发现可以保证唯一性的一方具备着顺序如 a b c ...


* 所以可以使用TreeMap集合。


* 这个集合最终应该存储的是字母和次数的对应关系。


* 1,因为操作的是字符串中的字母,所以先将字符串变成字符数组。


* 2,遍历字符数组,用每一个字母作为键去查Map集合这个表。


* 如果该字母键不存在,就将该字母作为键 1作为值存储到map集合中。


* 如果该字母键存在,就将该字母键对应值取出并+1,在将该字母和+1后的值存储到map集合中,


* 键相同值会覆盖。这样就记录住了该字母的次数.


* 3,遍历结束,map集合就记录所有字母的出现的次数。oy.


*/


public class ThreadDemo {


        /**


         * @param args


         */


        public static void main(String[] args) {


                 String str = "fdg+avAdc  bs5dDa9c-dfs";


                 String s = getCharCount(str);


                 System.out.println(s);


        }


        public static String getCharCount(String str) {


                 //将字符串变成字符数组


                 char[] chs = str.toCharArray();


                 //定义map集合表。


                 Map<Character,Integer> map = new TreeMap<Character,Integer>();


                 for (int i = 0; i < chs.length; i++) {


                         if(!(chs[i]>='a' && chs[i]<='z' || chs[i]>='A' && chs[i]<='Z'))


                                  continue;


                         //将数组中的字母作为键去查map表。                      


                         Integer value = map.get(chs[i]);


                         map.put(chs[i], value==null?1:value+1);                        


                 }


                 return mapToString(map);


        }


        private static String mapToString(Map<Character, Integer> map) {


                 StringBuilder sb = new StringBuilder();


                 Iterator<Character> it = map.keySet().iterator();


                 while(it.hasNext()){


                         Character key = it.next();


                         Integer value = map.get(key);


                         sb.append(key+"("+value+")");


                 }


                 return sb.toString();


        }


}