黑马程序员之Map

来源:互联网 发布:大数据分析系统翻译 编辑:程序博客网 时间:2024/04/30 14:55


------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

一、概述

       Map集合接口在JAVA中的util包中。在Map中存储的是键值对,它的key则是不能重复存储的,是唯一的。在Map接口中有很多的子类,本文只介绍它常用的两个子类,HashMap和TreeMap。

二、举例

       示例一、

/* * Map集合特点:存储的是键值对, 保证键的唯一性. * 1.存储 *   put(K key, V value)  *   putAll(Map<? extends K,? extends V> m)  *    * 2.删除 *   void clear() *   remove(Object key) *     * 3.判断 *   boolean containsKey(Object key) //集合中是否包含某个key *   boolean containsValue(Object value)//集合中是否包含某个value *   boolean isEmpty() *    * 4.获取 *   get(Object key) //根据指定的key获取value *   size() *   values() *  entrySet() //返回此映射中包含的映射关系的 Set视图 *   keySet() //返回此映射中包含的键的 Set视图 *    *    * Map *  |--HashTable: 底层是hash表数据结构, 键和值都不能为null, 该集合是线程同步的 *  |--HashMap: 底层是hash表数据结构, 键和值允许为null, 该集合是线程不同步的 *  |--TreeMap: 底层是二叉树数据结构, 线程不同步, 可以用于给map集合中的键排序 *   * Set集合底层使用了Map集合. *  *  */public class MapDemo {public static void main(String[] args) {Map<String, String> map = new HashMap<String, String>();//添加元素, //如果该key不存在, 则添加进去, 并返回null. //如果该key已经在集合中存在, 则后添加的value覆盖原来对应的value, 并返回原来对应的valuemap.put("01", "张三");map.put("02", "李四");map.put("03", "王五");map.put("04", "找牛");//判断是否包含01keyboolean b = map.containsKey("01");System.out.println(b);//判断是否包含valueb = map.containsValue("张三");System.out.println(b);//判断是否为空b = map.isEmpty();System.out.println(b);//返回集合中有多少元素int size = map.size();System.out.println(size);//返回key对应的value, 如果该key不存在, 则返回nullString s = map.get("01");System.out.println(s);//根据key删除该键值对, 并返回该key对应的valueString str = map.remove("01");System.out.println(str);//返回Map集合中所有的valueCollection<String> coll = map.values();for(Iterator<String> it = coll.iterator();it.hasNext();){System.out.println(it.next());}//返回Map集合中所有的keySet<String> set = map.keySet();for(Iterator<String> it = set.iterator();it.hasNext();){String key = it.next();System.out.println("key : " + key);String value = map.get(key);System.out.println("value : " + value);}}}

        示例二、

/* * Map集合的两种取出方式: *    Set<k> keySet: 将map中所有的key存入了set集合中 *        *       Map集合的取出原理: 将Map集合转成Set集合, 再通过迭代器取出. *        *    Set<Map.Entry<K,V>> entrySet: 将Map集合中的映射关系存入Set集合中, 这个关系的数据类型就是: Map.Entry *     *    Map.Entry:  *        Entry是一个接口, 它是Map中的一个内部接口. *  *  *  */public class MapDemo2 {public static void main(String[] args) {Map<String, String> map = new HashMap<String, String>();map.put("01", "张三");map.put("02", "李四");map.put("03", "王五");map.put("04", "找牛");Set<String> set = map.keySet();for(Iterator<String> it = set.iterator();it.hasNext();){String key = it.next();String value = map.get(key);System.out.println(value);}Set<Map.Entry<String, String>> setEntry = map.entrySet();for(Iterator<Map.Entry<String, String>> it = setEntry.iterator();it.hasNext();){Map.Entry<String, String> en = it.next();String key = en.getKey();System.out.println("key : " + key);if("01".equals(key))en.setValue("zhangsan");String value = en.getValue();System.out.println("value : " + value);}}}

        示例三、TreeMap示例

//按照学生的年龄进行升序排序public class TreeMap练习 {public static void main(String[] args) {Map<Student, String> map = new TreeMap<Student, String>(new Comp());map.put(new Student("t", 12), "dadadadadafaf");map.put(new Student("J", 7), "dadadewd");map.put(new Student("a", 5), "dadadad444");Set<Map.Entry<Student, String>> entries = map.entrySet();for (Iterator<Map.Entry<Student, String>> it = entries.iterator(); it.hasNext();) {Map.Entry<Student, String> me = it.next();Student s = me.getKey();System.out.println("student -> " + s);String addr = me.getValue();System.out.println("addr -> " + addr);}}}//自定义比较器class Comp implements Comparator<Student>{@Overridepublic int compare(Student o1, Student o2) {int num = (o1.getName().compareTo(o2.getName()))*1;//System.out.println(" --------------- " + num);if(0==num)return (new Integer(o1.getAge()).compareTo(new Integer(o2.getAge())));return num;}}
class Student implements Comparable<Student> {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic boolean equals(Object obj) {if (!(obj instanceof Student))// throw new RuntimeException("类型匹配错误!");throw new ClassCastException("类型不匹配.");Student stu = (Student) obj;return (this.getName().equals(stu.getName()) && this.getAge() == stu.getAge());}@Overridepublic int hashCode() {return this.getName().hashCode() + this.getAge() * 27;}@Overridepublic String toString() {return "Name : " + this.getName() + ", age : " + this.getAge();}@Overridepublic int compareTo(Student o) {int num = new Integer(this.age).compareTo(new Integer(o.getAge()));if (0 == num)return this.getName().compareTo(o.getName());return num;}}


        示例四、

//统计字符串中字符出现的次数, 如: "adadggwsf", 统计面一个字符出现的次数//打印为:a(2)d(2).....public class TreeMap练习2 {public static void main(String[] args) {String str = "adadg,.g;wsf";char[] ch = new char[str.length()];str.getChars(0, str.length(), ch, 0);// for(int i =0;i<ch.length;i++){// System.out.println(ch[i]);// }Map<Character, Integer> map = new TreeMap<Character, Integer>();//遍历char数组for (int i = 0; i < ch.length; i++) {char temp = ch[i];if(!(temp>='a'&&temp<='z')||(temp>='A'&&temp<='Z'))continue;Character c = new Character(temp);//如果key存在, 则取出value, 并+1, 再存进去;//如果key不存在, 则直接存进去, value = 1if (map.containsKey(c)) {map.put(c, map.get(c).intValue() + 1);} else {map.put(c, new Integer(1));}}//迭代器遍历Map集合StringBuilder sb = new StringBuilder();Set<Map.Entry<Character, Integer>> set = map.entrySet();for (Iterator<Map.Entry<Character, Integer>> it = set.iterator(); it.hasNext();) {Map.Entry<Character, Integer> me = it.next();String key = Character.toString(me.getKey().charValue());String value = Integer.toString(me.getValue().intValue());sb.append(key + "(" + value + ")");}System.out.println(sb.toString());}}



0 0
原创粉丝点击