Map集合

来源:互联网 发布:下列网络系统安全原则 编辑:程序博客网 时间:2024/05/17 05:16

Map集合:

该集合存放键-值对,且要保证键的唯一性。

---Hashtable:底层是哈希表数据结构,不可以存入null值和null键。该集合是线程同步的

---HashMap:底层是哈希表数据结构,允许使用null值和null键,该集合是不同步的

---TreeMap:底层是二叉树数据结构。线程不同步,可以用于给map集合中的键进行排序

(一) 主要操作:

1.添加

         put(Kkey, V value);

         putAll(Map<?extends  K, ? extends V> m);

         说明:如果出现相同的键,那么后添加的值会覆盖原有值

2.删除

         clear();

         remove(Objectkey)

3.判断

         containsValue(Objectvalue)

         containsKey(Objectkey)

         isEmpty();

4.获取

         get(Objectkey);

         size();

         values();

 

         entrySet();

         keySet();

程序示例:

publicstatic void basicMapDemo()

{

Map<String, String> map = newHashMap<String, String>();

//添加元素

map.put("001", "huanhuan");

map.put("002", "beibei");

map.put("003", "fanfan");

System.out.println(map);

//判断

System.out.println("exsit??? " +map.containsKey("001"));

System.out.println("exsit??? " +map.containsValue("beibei"));

//删除

String str = map.remove("002");

System.out.println(str);

System.out.println(map);

//获取

System.out.println(map.get("001"));

map.put("002", "beibei");

map.put("001","zhaoxiaoleng");//键值同前面相同,会覆盖

map.put("004", "family");

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

System.out.println(coll);

}

map集合的两种取出方式:

1.      Set<k>keySet():

map中所有的键存入Set集合,因为Set具备迭代器

         可以通过迭代方式取出所有的键,再根据get方法获取每一个键对应的值

程序示例:

       publicstatic void mapGet1()

       {

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

              map.put("001","huanhuan");

              map.put("002","beibei");

              map.put("003","fanfan");

              //先获取map集合的所有键的Set集合,keySet()

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

              //迭代取出所有的键

              for(Iterator<String>iter = keySet.iterator(); iter.hasNext(); )

              {

                     Stringkey = iter.next();

                     Stringvalue = map.get(key);

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

              }

        }

2.      Set<Map.Entry<k,v>>entrySet:

map集合中的映射关系存入到了Set集合中

         而这个关系的数据类型就是:Map.Entry。它返回此映射中包含的映射关系的 Set视图

程序示例:

       publicstatic void mapGet2()

       {

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

              map.put("001","huanhuan");

              map.put("002","beibei");

              map.put("003","fanfan");

              //获得映射关系的集合——entrySet()

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

              //迭代取关系

              for(Iterator<Map.Entry<String,String>> iter = entrySet.iterator(); iter.hasNext(); )

              {

                     Map.Entry<String,String> entry = iter.next();

                     String key =entry.getKey();

                     String value = entry.getValue();

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

               }

        }

练习:

(一)  问题描述:

         1.每一个学生都有对应的归属地

         2.学生属性:姓名、年龄

         3.姓名和年龄相同的视为同一个学生

要求:

1.描述学生

2.定义map集合,将学生作为键,归属地作为值存入

3.获取map集合中的元素

程序示例:

importjava.util.*;

classNameComparator implements Comparator<Student>

{

       public int compare(Student stu1, Studentstu2)

       {

              int result =(stu1.getName()).compareTo(stu2.getName());

              if(0 == result)

                     return newInteger(stu1.getAge()).compareTo(new Integer(stu2.getAge()));

              return result;

       }

}

classStudent implements Comparable<Student>

{

       private String name;

       private int age;

       Student(String name, int age)

       {

              this.name = name;

              this.age = age;

       }

       public int hashCode()//存放到哈希表里,要自定义地址,减少地址冲突

       {

              return name.hashCode() + age*34;

       }

       public boolean equals(Object obj)//比较,保证学生唯一

       {

              if(!(obj instanceof Student))

                     throw newClassCastException("类型不匹配");

              Student stu = (Student)obj;

              boolean result =(this.name.equals(stu.name)) && (this.age == stu.age);

              return result;

       }

       public int compareTo(Student stu)//存放到二叉树中,要让元素具备一定的顺序

       {

              int result = (newInteger(this.age)).compareTo(new Integer(stu.age));

              return result;

       }

       public String getName()

       {

              return name;

       }

       public int getAge()

       {

              return age;

       }

}

publicclass MapTest

{

       public static void mapTestDemo1()

       {

              HashMap<Student, String>hashMap = new HashMap<Student, String>();

              hashMap.put(newStudent("hh", 21), "linyi");

              hashMap.put(newStudent("hh", 22), "linyi");

              hashMap.put(newStudent("ff", 23), "weifang");

              hashMap.put(newStudent("bb", 1), "jining");

              /*

              //方式一:

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

              for(Iterator<Map.Entry<Student,String>>iter=entrySet.iterator();iter.hasNext(); )

              {

                     Map.Entry<Student,String> entry = iter.next();

                     Student stu =entry.getKey();

                     String add =entry.getValue();

                     System.out.println("姓名:" + stu.getName()+ " 年龄:"+ stu.getAge() + "  来自于:" + add);

              }

              */

              //方式二:

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

              for(Iterator<Student> iter =keySet.iterator(); iter.hasNext(); )

              {

                     Student key = iter.next();

                     String value =hashMap.get(key);//归属地

                     System.out.println("姓名:" + key.getName()+ " 年龄:"+ key.getAge() + " 来自:"+ value);

              }

       }

       //对学生进行排序

       public static void mapTestDemo2()

       {

              TreeMap<Student, String>treeMap = new TreeMap<Student, String>(new NameComparator());//易错

              treeMap.put(newStudent("xiaoleng", 22), "linyi");

              treeMap.put(newStudent("fanfan", 23), "weifang");

              treeMap.put(newStudent("beibei", 1), "jining");

              treeMap.put(newStudent("family", 1), "qufu");

 

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

              for(Iterator<Map.Entry<Student,String>> iter = entrySet.iterator(); iter.hasNext(); )//易错,迭代器泛型跟Set一致

              {

                     Map.Entry<Student,String> entry = iter.next();

                     Student stu = entry.getKey();

                     String addr =entry.getValue();

                     System.out.println(stu.getName()+"  "+stu.getAge()+"  "+ addr);

              }

       }

       public static void main(String[] args)

       {

              mapTestDemo1();

              System.out.println("------------------------");

              mapTestDemo2();

       }

}

总结:在描述对象的类中一定覆写hashCode(), equals(), compareTo()等方法,因为对象将来可能被存入到哈希表结构或者二叉树结构的集合中。

(二)  问题描述:

获取给定字符串(如"ajosidiea")中的字母出现的次数,

并按此格式打印:a(1)b(2)......

通过打印格式发现,每一个字母都有对应的次数,即存在映射关系。

此时,可以考虑选择Map集合。

思路:

1.将字符串转换成字符数组

2.定义一个Map集合,因为打印结果有顺序,故选择TreeMap集合

3.遍历字符数组。

         将每一个字符作为键去查Map集合

如果返回null,将该字母和 1存入到Map集合中,否则,修改出现次数后重新存入

4.Map集合中的数据转换成字符串形式打印

程序示例:

importjava.util.*;

publicclass MapTest2

{

       public static String charCount(Stringstr)

       {

              char chs[] = str.toCharArray();

              TreeMap<Character, Integer>treeMap = new TreeMap<Character, Integer>();

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

              {

                     Integer value =treeMap.get(chs[i]);//取出键对应的值

                     if(null == value)//判断是否已存在,可以换种写法

                     {

                            treeMap.put(chs[i],1);

                     }

                     else

                     {

                            value += 1;

                            treeMap.put(chs[i],value);

                     }

              }

              StringBuilder strBuil = newStringBuilder();//缓冲区,用于存放取出的键-值对,以便于转换成字符串

              Set<Map.Entry<Character,Integer>> entrySet = treeMap.entrySet();

              for(Iterator<Map.Entry<Character,Integer>> iter = entrySet.iterator(); iter.hasNext(); )

              {

                     Map.Entry<Character,Integer> entry = iter.next();

                     char ch = entry.getKey();

                     int count =entry.getValue();

                     strBuil.append(ch+"("+count+")");

              }

              return strBuil.toString();

       }

       public static void main(String[] args)

       {

              String str = charCount("bacfabcac");

              System.out.println(str);

       }

}

PS:判断语句部分还可以写成:

intcount = 0;

if(!(null== value))

       count = value;

count++;

treeMap.put(chs[i],count);