java Map的子类-java学习笔记

* 作为学生来说,是根据学号来区分不同的学生的,那么假设我现在已经知道了学生的学号,我要根据学号去获取学生姓名,请问怎么做呢?

 * 如果采用前面讲解过的集合,我们只能把学号和学生姓名作为一个对象的成员,然后存储整个对象,将来遍历的时候,判断,获取对应的名称。

 * 但是呢,如果我都能把学生姓名拿出来了,我还需要根据编号去找吗?

 * 针对我们目前的这种需求:仅仅知道学号,就想知道学生姓名的情况,Java就提供了一种新的集合 Map。

 * 通过查看API,我们知道Map集合的一个最大的特点,就是它可以存储键值对的元素。这个时候存储我们上面的需求,就可以这样做

 *          学号1           姓名1

 *          学号2        姓名2

 *          学号3           姓名3

 *          学号2(不行)姓名4

 *          学号4      姓名4

  • Map集合的特点:

 *          将键映射到值的对象。一个映射不能包含重复的键;每个键最多只能映射到一个值。

 *

  • Map集合和Collection集合的区别?

 *          Map集合存储元素是成对出现的,Map集合的键是唯一的,值是可重复的。可以把这个理解为:夫妻对

 *          Collection集合存储元素是单独出现的,Collection的儿子Set是唯一的,List是可重复的。可以把这个理解为:光棍(11.11)

 *

 * 注意:

 *          Map集合的数据结构值针对键有效,跟值无关      

 *                 HashMap,TreeMap等会讲。

 *           Collection集合的数据结构是针对元素有效

 * Map集合的功能概述:

 * 1:添加功能

 *          V put(K key,V value):添加元素。这个其实还有另一个功能?先不告诉你,等会讲

 *                 如果键是第一次存储,就直接存储元素,返回null

 *                 如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值

 * 2:删除功能

 *          void clear():移除所有的键值对元素

 *          V remove(Object key):根据键删除键值对元素,并把值返回

 * 3:判断功能

 *          boolean containsKey(Object key):判断集合是否包含指定的键

 *          boolean containsValue(Object value):判断集合是否包含指定的值

 *          boolean isEmpty():判断集合是否为空

 * 4:获取功能

 *          Set<Map.Entry<K,V>> entrySet():???

 *          V get(Object key):根据键获取值

 *          Set<K> keySet():获取集合中所有键的集合

 *          Collection<V> values():获取集合中所有值的集合

 * 5:长度功能

 *          int size():返回集合中的键值对的对数

public class MapDemo {

       public static void main(String[] args) {

              // 创建集合对象

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



              // 添加元素

              // V put(K key,V value):添加元素。这个其实还有另一个功能?先不告诉你,等会讲

              // System.out.println("put:" + map.put("文章", "马伊俐"));null

              // System.out.println("put:" + map.put("文章", "姚笛"));马伊俐



              map.put("邓超", "孙俪");

              map.put("黄晓明", "杨颖");

              map.put("周杰伦", "蔡依林");

              map.put("刘恺威", "杨幂");



              // void clear():移除所有的键值对元素

              // map.clear();



              // V remove(Object key):根据键删除键值对元素,并把值返回

              // System.out.println("remove:" + map.remove("黄晓明"));孙俪

              // System.out.println("remove:" + map.remove("黄晓波"));null



              // boolean containsKey(Object key):判断集合是否包含指定的键

              // System.out.println("containsKey:" + map.containsKey("黄晓明")); true

              // System.out.println("containsKey:" + map.containsKey("黄晓波"));false



              // boolean isEmpty():判断集合是否为空

              // System.out.println("isEmpty:"+map.isEmpty());false

              //int size():返回集合中的键值对的对数

              System.out.println("size:"+map.size());4

              // 输出集合名称

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

       }

}

       (4)Map集合的遍历

              A:键找值

                     a:获取所有键的集合

                     b:遍历键的集合,得到每一个键

                     c:根据键到集合中去找值

             

              B:键值对对象找键和值

                     a:获取所有的键值对对象的集合

                     b:遍历键值对对象的集合,获取每一个键值对对象//me是对象

String key = me.getKey();

                            String value = me.getValue();

                     c:根据键值对对象去获取键和值

                    

              代码体现:

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

                     hm.put("it002","hello");

                     hm.put("it003","world");

                     hm.put("it001","java");

                    

                     //方式1 键找值

                     Set<String> set = hm.keySet();

                     for(String key : set) {

                            String value = hm.get(key);

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

                     }

                    

                     //方式2 键值对对象找键和值

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

                     for(Map.Entry<String,String> me : set2) {

                            String key = me.getKey();

                            String value = me.getValue();

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

                     }

       (5)HashMap集合的练习

              A:HashMap<String,String>

              B:HashMap<Integer,String>

              C:HashMap<String,Student>

              D:HashMap<Student,String>//需要重写Hashcode和equals因为键用的是哈希表

  • LinkedHashMap:是Map接口的哈希表和链接列表实现,具有可预知的迭代顺序。
  • 由哈希表保证键的唯一性
  • 由链表保证值的有序(存储和取出的顺序一致)

       (6)TreeMap集合的练习           

              A:TreeMap<String,String>

  B:TreeMap<Student,String>//需要实现Comparactor接口

public class TreeMapDemo {



       public static void main(String[] args) {

              // TODO Auto-generated method stub

              TreeMap<Student, Integer> th = new TreeMap<Student, Integer>(new Comparator<Student>() {



                     @Override

                     public int compare(Student s1, Student s2) {

                            // TODO Auto-generated method stub

                            //主要条件按照年龄排序

       int num = s1.getAge() - s2.getAge();

                            //次要条件

Int num2=num==0?s1.getName().compareTo(s2.getName()):num;

                            return num2;

                     }

              });



       Student s = new Student("张三", 25);

       Student s2 = new Student("李四", 25);

       Student s3 = new Student("王二", 25);

       Student s4 = new Student("麻子", 25);

       Student s5 = new Student("小明", 25);

       Student s6 = new Student("二愣", 25);



              th.put(s, 222);

              th.put(s2, 333);

              th.put(s3, 655);

              th.put(s4, 789);

              th.put(s5, 325);

              th.put(s6, 125);

              Set<Student> set = th.keySet();

              for (Student key : set) {

                     Integer i = th.get(key);

                     System.out.println(key + "---" + i);
              }
       }
}

      

(7)案例

           A:统计一个字符串中每个字符出现的次数

public class Demo_1 {

       public static void main(String[] args) {

              // TODO Auto-generated method stub

              int count = 0;

              // 定义一个字符串

              String s = "我啊是uahhaiueghv阿强";

              // 定义一个hashmap

              //因为TreeMap实现了Comparable接口所以可以实现排序所以使用TreeMap

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

              //把字符串转成字符数组

              char[] c = s.toCharArray();

              Set<Character> set = ha.keySet();

              for (char i : c) {

                     //得到值

Integer in = ha.get(i);// 得到值也就是个数然后覆盖****
                     if (!ha.containsKey(i)) {

                            ha.put(i, 1);

                     } else {

                            //重新覆盖值

put(i, ++in);
                     }

              }

              //字符串缓冲区

              StringBuilder sb = new StringBuilder();

              for (Character ch : set) {

                     //这个必须这样写因为这个没遍历都会出现一次添加****

append(ch).append('(').append(ha.get(ch)).append(')');
              }

              System.out.println(sb.toString());

       }
}

B:集合的嵌套遍历

  a:HashMap嵌套HashMap

public class HashMapDemo {


       public static void main(String[] args) {

              // TODO Auto-generated method stub

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



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


Student s = new Student("张三", 25);

Student s2 = new Student("李四", 25);

Student s3 = new Student("王二", 25);

       Student s4 = new Student("麻子", 25);

       Student s5 = new Student("小明", 25);

       Student s6 = new Student("二愣", 25);



              ha1.put("100", s);

              ha1.put("101", s2);

              ha1.put("102", s3);

              ha1.put("103", s4);

              ha1.put("104", s5);

              ha1.put("105", s6);



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

Student s11 = new Student("狗蛋", 25);

Student s22 = new Student("黑子", 20);

Student s33 = new Student("狗子", 26);

Student s44 = new Student("耗子", 15);

Student s55 = new Student("铁蛋", 16);

Student s66 = new Student("小黑", 24);



              ha2.put("201", s11);

              ha2.put("202", s22);

              ha2.put("203", s33);

              ha2.put("204", s44);

              ha2.put("205", s55);

              ha2.put("206", s66);



              ha.put("jc", ha1);

              ha.put("jy", ha2);

              Set<String> set = ha.keySet();

              for (String ss : set) {

                     HashMap<String, Student> h = ha.get(ss);

                     Set<String> ser_2 = h.keySet();

                     for (String hh : ser_2) {

                            System.out.println(h.get(hh).getName()+"---"+h.get(hh).getAge()+"---"+hh);

                     }



              }

       }
}

  b:HashMap嵌套ArrayList

public class HashMaptoArrayList {


       public static void main(String[] args) {

              // TODO Auto-generated method stub


              HashMap<String, ArrayList<String>> hatolist = new HashMap<String, ArrayList<String>>();



              ArrayList<String> list = new ArrayList<String>();



              list.add("张飞");

              list.add("吕布");

              list.add("貂蝉");

              list.add("曹操");

              list.add("关羽");



              ArrayList<String> list_2 = new ArrayList<String>();



              list_2.add("孙悟空");

              list_2.add("唐玄藏");

              list_2.add("猪八戒");

              list_2.add("沙悟净");

              list_2.add("白龙马");



              hatolist.put("三国演义", list);

              hatolist.put("西游记", list_2);

              //得到健

              Set<String> s = hatolist.keySet();

              for (String ss : s) {

                     System.out.println(ss);

                     ArrayList<String> arr = hatolist.get(ss);

                     for(String sss:arr){

                            System.out.println("\t"+sss);

                     }
              }
       }

}

  c:ArrayList嵌套HashMap

public class ArrayListtoHashMap {



       public static void main(String[] args) {

              // TODO Auto-generated method stub



              ArrayList<HashMap<Integer, String>> arr = new ArrayList<HashMap<Integer, String>>();



              HashMap<Integer, String> ha = new HashMap<Integer, String>();



              ha.put(100, "张三");

              ha.put(101, "李四");

              ha.put(102, "王二");

              ha.put(103, "麻子");

              ha.put(104, "小明");

              ha.put(105, "二愣");



              HashMap<Integer, String> ha1 = new HashMap<Integer, String>();



              ha1.put(201, "狗蛋");

              ha1.put(202, "铁蛋");

              ha1.put(203, "耗子");

              ha1.put(204, "华子");

              ha1.put(205, "柳家");



              arr.add(ha);

              arr.add(ha1);



              for (HashMap<Integer, String> h : arr) {

                     Set<Integer> set = h.keySet();

                     for(Integer i:set){

                            System.out.println(i+"---"+h.get(i));

                     }

                     System.out.println();

              }


       }

}

  d:多层嵌套

      

              public class HashMapDemo {

       public static void main(String[] args) {

              // 创建大集合

              HashMap<String, HashMap<String, ArrayList<Student>>> czbkMap = new HashMap<String, HashMap<String, ArrayList<Student>>>();



              // 北京校区数据

              HashMap<String, ArrayList<Student>> bjCzbkMap = new HashMap<String, ArrayList<Student>>();

              ArrayList<Student> array1 = new ArrayList<Student>();

              Student s1 = new Student("林青霞", 27);

              Student s2 = new Student("风清扬", 30);

              array1.add(s1);

              array1.add(s2);

              ArrayList<Student> array2 = new ArrayList<Student>();

              Student s3 = new Student("赵雅芝", 28);

              Student s4 = new Student("武鑫", 29);

              array2.add(s3);

              array2.add(s4);

              bjCzbkMap.put("基础班", array1);

              bjCzbkMap.put("就业班", array2);

              czbkMap.put("北京校区", bjCzbkMap);



              // 晚上可以自己练习一下

              // 上海校区数据自己做

              // 广州校区数据自己做

              // 西安校区数据

              HashMap<String, ArrayList<Student>> xaCzbkMap = new HashMap<String, ArrayList<Student>>();

ArrayList<Student> array3 = new ArrayList<Student>();

Student s5 = new Student("范冰冰", 27);

       Student s6 = new Student("刘意", 30);

              array3.add(s5);

              array3.add(s6);

              ArrayList<Student> array4 = new ArrayList<Student>();

              Student s7 = new Student("李冰冰", 28);

              Student s8 = new Student("张志豪", 29);

              array4.add(s7);

              array4.add(s8);

xaCzbkMap.put("基础班", array3);

xaCzbkMap.put("就业班", array4);

czbkMap.put("西安校区", xaCzbkMap);

              // 遍历集合

Set<String> czbkMapSet = czbkMap.keySet();

for (String czbkMapKey : czbkMapSet) {

                     System.out.println(czbkMapKey);

HashMap<String,ArrayList<Student>> czbkMapValue=czbkMap.get(czbkMapKey);

Set<String> czbkMapValueSet = czbkMapValue.keySet();

for (String czbkMapValueKey : czbkMapValueSet) {

System.out.println("\t"+czbkMapValueKey);

ArrayList<Student> czbkMapValueValue = czbkMapValue.get(czbkMapValueKey);

for (Student s : czbkMapValueValue) {

                                   System.out.println("\t\t" + s.getName() + "---"

                                                 + s.getAge());

                            }

                     }

              }

       }

}

* 1:Hashtable和HashMap的区别?

 * Hashtable:线程安全,效率低。不允许null键和null值

 * HashMap:线程不安全,效率高。允许null键和null值

* 2:List,Set,Map等接口是否都继承子Map接口?

 * List,Set不是继承自Map接口,它们继承自Collection接口

 * Map接口本身就是一个顶层接口

public class HashtableDemo {

       public static void main(String[] args) {

              // HashMap<String, String> hm = new HashMap<String, String>();

              Hashtable<String, String> hm = new Hashtable<String, String>();



              hm.put("it001", "hello");

              // hm.put(null, "world"); //NullPointerException

              // hm.put("java", null); // NullPointerException

              System.out.println(hm);

       }

}

2:Collections(理解)     

       (1)是针对集合进行操作的工具类

       (2)面试题:Collection和Collections的区别

              A:Collection 是单列集合的顶层接口,有两个子接口List和Set

              B:Collections 是针对集合进行操作的工具类,可以对集合进行排序和查找等

       (3)常见的几个小方法:

* Collections:是针对集合进行操作的工具类,都是静态方法。

       * 要知道的方法

  • public static <T> void sort(List<T> list):排序 默认情况下是自然顺序。
  • public static <T> int binarySearch(List<?> list,T key):二分查找
  • public static <T> T max(Collection<?> coll):最大值
  • public static void reverse(List<?> list):反转
  • * public static void shuffle(List<?> list):随机置换
  • (4)案例

  A:ArrayList集合存储自定义对象的排序

public class ListDemo {

       public static void main(String[] args) {

ArrayList<Student> arr = new ArrayList<Student>();

             

       Student s = new Student("张三", 15);

       Student s2 = new Student("李四", 24);

       Student s3 = new Student("王二", 23);

       Student s4 = new Student("麻子", 25);

       Student s5 = new Student("小明", 55);

       Student s6 = new Student("二愣", 65);



              arr.add(s);

              arr.add(s6);

              arr.add(s2);

              arr.add(s3);

              arr.add(s4);

              arr.add(s5);

             

sort(arr,new Comparator<Student>() {
                     @Override

                     public int compare(Student s1, Student s2) {

                            // TODO Auto-generated method stub

       int num=s1.getAge()-s2.getAge();

int num2=num==0?s1.getName().compareTo(s2.getName()):num;

                            return num2;

                     }

              });

              for(Student ss:arr){

                     System.out.println(ss);

              }

       }

}

              B:模拟斗地主洗牌和发牌

C:模拟斗地主洗牌和发牌并对牌进行排序

/*

 * 思路:

 *          A:创建一个HashMap集合

 *          B:创建一个ArrayList集合

 *          C:创建花色数组和点数数组

 *          D:从0开始往HashMap里面存储编号,并存储对应的牌

 *        同时往ArrayList里面存储编号即可。

 *      E:洗牌(洗的是编号)

 *      F:发牌(发的也是编号,为了保证编号是排序的,就创建TreeSet集合接收)

 *      G:看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌)

 */

public class PokerDemo {

       public static void main(String[] args) {

              // 创建一个HashMap集合

              HashMap<Integer, String> hm = new HashMap<Integer, String>();



              // 创建一个ArrayList集合

              ArrayList<Integer> array = new ArrayList<Integer>();



              // 创建花色数组和点数数组

              // 定义一个花色数组

              String[] colors = { "♠", "♥", "♣", "♦" };

              // 定义一个点数数组

              String[] numbers = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q",

                            "K", "A", "2", };



              // 从0开始往HashMap里面存储编号,并存储对应的牌,同时往ArrayList里面存储编号即可。

              int index = 0;

              for (String number : numbers) {

                     for (String color : colors) {

                            String poker = color.concat(number);

                            hm.put(index, poker);

                            array.add(index);

                            index++;

                     }

              }

              hm.put(index, "小王");

              array.add(index);

              index++;

              hm.put(index, "大王");

              array.add(index);



              // 洗牌(洗的是编号)

              Collections.shuffle(array);



              // 发牌(发的也是编号,为了保证编号是排序的,就创建TreeSet集合接收)

TreeSet<Integer> fengQingYang = new TreeSet<Integer>();
TreeSet<Integer> linQingXia = new TreeSet<Integer>();
TreeSet<Integer> liuYi = new TreeSet<Integer>();
TreeSet<Integer> diPai = new TreeSet<Integer>();


              for (int x = 0; x < array.size(); x++) {

                     if (x >= array.size() - 3) {

                            diPai.add(array.get(x));

                     } else if (x % 3 == 0) {

                            fengQingYang.add(array.get(x));

                     } else if (x % 3 == 1) {

                            linQingXia.add(array.get(x));

                     } else if (x % 3 == 2) {

                            liuYi.add(array.get(x));

                     }

              }



              // 看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌)

              lookPoker("风清扬", fengQingYang, hm);

              lookPoker("林青霞", linQingXia, hm);

              lookPoker("刘意", liuYi, hm);

              lookPoker("底牌", diPai, hm);

       }



       // 写看牌的功能

       public static void lookPoker(String name, TreeSet<Integer> ts,

                     HashMap<Integer, String> hm) {

              System.out.print(name + "的牌是:");

              for (Integer key : ts) {

                     String value = hm.get(key);

                     System.out.print(value + " ");

              }

              System.out.println();

       }

}

 转载 http://www.51csdn.cn/article/223.html

猜你喜欢

转载自blog.csdn.net/qq_43599835/article/details/84339174