黑马程序员——JAVA集合

来源:互联网 发布:沉迷网络的哲学文章 编辑:程序博客网 时间:2024/05/17 07:17

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

Map、HashMap、TreeMap

    Map:一次添加一对元素,Collection一次添加一个元素。
    Map也称为双列集合,Collection集合称为单列集合。
    其实Map集合中存储的就是键值对。
    map集合中必须保证键的唯一性。

常用方法:
    1、添加
    value put(key,value):返回前一个和key关联的值,如果没有返回null。

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

    3、判断
    boolean containsKey(key);
    boolean containsValue(value);
    boolean isEmpty();

    4、获取
    value get(key):通过键获取值,如果没有该键返回null。
                            当然可以通过返回null,来判断是否包含指定键。
    int size():获取键值对个数。


示例1:
  1. import java.util.HashMap;
  2. import java.util.Map;

  3. public class MapDemo{
  4.        public static void main(String[] args){
  5.             Map<Integer,String> map = new HashMap<Integer,String>();
  6.              method(map);
  7.       }

  8.        public static void method(Map<Integer,String> map){ //学号和姓名
  9.              //添加元素
  10.             System. out.println(map.put(8,"旺财" ));
  11.             System. out.println(map.put(8,"小强" ));
  12.             System. out.println(map);

  13.             map.put(2, "张三");
  14.             map.put(7, "赵六");
  15.             System. out.println(map);

  16.              //删除
  17.             System. out.println("remove:" + map.remove(2));

  18.              //判断
  19.             System. out.println("containsKey:" + map.containsKey(7));

  20.              //获取
  21.             System. out.println("get:" + map.get(7));
  22.       }
  23. }

运行结果:
获取Map集合元素并打印方式一:

示例2:
  1. import java.util.HashMap;
  2. import java.util.Iterator;
  3. import java.util.Map;
  4. import java.util.Set;

  5. public class MapDemo{
  6.        public static void main(String[] args){
  7.             Map<Integer,String> map = new HashMap<Integer,String>();
  8.             method(map);
  9.       }

  10.        public static void method(Map<Integer,String> map){
  11.             map.put(8, "王五");
  12.             map.put(2, "赵六");
  13.             map.put(7, "小强");
  14.             map.put(6, "旺财");

  15.              //取出map中的所有元素。
  16.              //原理,通过keySet方法获取map中所有的键所在的set集合,在通过set的迭代器获取到每一个键。
  17.              //再对每一个键通过map集合的get方法获取其对应的值即可。

  18.             Set<Integer> keySet = map.keySet();
  19.             Iterator<Integer> it = keySet.iterator();

  20.              while(it.hasNext()){
  21.                   Integer key = it.next();
  22.                   String value = map.get(key);
  23.                   System.out.println(key + ":" + value);
  24.             }
  25.       }
  26. }
 运行结果:


 获取Map集合元素并打印方式二:

示例3:
  1. import java.util.HashMap;
  2. import java.util.Iterator;
  3. import java.util.Map;
  4. import java.util.Set;

  5. public class MapDemo{
  6.        public static void main(String[] args){
  7.             Map<Integer,String> map = new HashMap<Integer,String>();
  8.              method(map);
  9.       }

  10.        public static void method(Map<Integer,String> map){
  11.             map.put(8, "王五");
  12.             map.put(2, "赵六");
  13.             map.put(7, "小强");
  14.             map.put(6, "旺财");

  15.              /*
  16.             通过Map转成Set就可以迭代。
  17.             找到了另一个方法,entrySet。
  18.             该方法将键和值的映射关系作为对象存储到了Set集合中,而这个映射关系的类型就是Map.Entry类型
  19.             */
  20.             Set<Map.Entry<Integer,String>> entrySet = map.entrySet();

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

  22.              while(it.hasNext()){
  23.                   Map.Entry<Integer,String> me = it.next();
  24.                   Integer key = me.getKey();
  25.                   String value = me.getValue();
  26.                   System. out.println(key + ":" + value);
  27.             }
  28.       }
  29. }
运行结果:


获取Map集合元素并打印方式三:

示例4:
  1. import java.util.Collection;
  2. import java.util.HashMap;
  3. import java.util.Iterator;
  4. import java.util.Map;

  5. public class MapDemo{
  6.        public static void main(String[] args){
  7.             Map<Integer,String> map = new HashMap<Integer,String>();
  8.              method(map);
  9.       }

  10.        public static void method(Map<Integer,String> map){
  11.             map.put(8, "王五");
  12.             map.put(2, "赵六");
  13.             map.put(7, "小强");
  14.             map.put(6, "旺财");

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

  16.             Iterator<String> it = values.iterator();
  17.              while(it.hasNext()){
  18.                   System. out.println(it.next());
  19.             }
  20.       }
  21. }
运行结果:


Map常用的子类:
          |--Hashtable:内部结构是哈希表,是同步的。不允许null作为键,null作为值。
               |--Properties:用来存储键值对型的配置文件的信息,可以和IO技术相结合。
          |--HashMap:内部结构式哈希表,不是同步的。允许null作为键,null作为值。
          |--TreeMap:内部结构式二叉树,不是同步的。可以对Map集合中的键进行排序。

hashSet实现Set接口,由哈希表(实际上是一个HashMap实例)支持。

示例5:
  1. import java.util.HashMap;
  2. import java.util.Iterator;

  3. class Student {
  4.        private String name;
  5.        private int age;

  6.        public Student(){
  7.       }

  8.        public Student(String name,int age){
  9.              this.name = name;
  10.              this.age = age;
  11.       }

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

  15.        public String getName(){
  16.              return this .name;
  17.       }

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

  21.        public int getAge(){
  22.              return this .age;
  23.       }

  24.        public int hashCode() {
  25.              final int prime = 31;
  26.              int result = 1;
  27.             result = prime * result + age;
  28.             result = prime * result + ((name == null) ? 0 : name.hashCode());
  29.              return result;
  30.       }

  31.        public boolean equals(Object obj) {
  32.              if (this == obj)
  33.                    return true ;
  34.              if (obj == null)
  35.                    return false ;
  36.              if (getClass() != obj.getClass())
  37.                    return false ;
  38.             Student other = (Student) obj;
  39.              if (age != other.age)
  40.                    return false ;
  41.              if (name == null) {
  42.                    if (other.name != null)
  43.                          return false ;
  44.             } else if (!name.equals(other.name))
  45.                    return false ;
  46.              return true ;
  47.       }
  48. }

  49. public class HashMapDemo{
  50.        public static void main(String[] args){
  51.              //将学生对象和学生的归属地通过键与值存储到map集合中
  52.             HashMap<Student,String> hm = new HashMap<Student,String>();

  53.             hm.put( new Student("lisi" ,38),"北京");
  54.             hm.put( new Student("zhaoliu" ,24),"上海");
  55.             hm.put( new Student("xiaoqiang" ,31),"沈阳");
  56.             hm.put( new Student("wangcai" ,28),"大连");
  57.             hm.put( new Student("zhaoliu" ,24),"铁岭");
  58.             
  59.             Iterator<Student> it = hm.keySet().iterator();

  60.              while(it.hasNext()){
  61.                   Student key = it.next();
  62.                   String value = hm.get(key);
  63.                   System.out.println(key.getName() + ":" + key.getAge() + "---" + value);
  64.             }
  65.       }
  66. }

运行结果:


P.S.
    键有了判断依据,HashMap中的值就被覆盖。

示例6:
  1. import java.util.Comparator;
  2. import java.util.Iterator;
  3. import java.util.Map;
  4. import java.util.TreeMap;

  5. class ComparatorByName implements Comparator<Student>{
  6.        public int compare(Student s1,Student s2){
  7.              int temp = s1.getName().compareTo(s2.getName());
  8.              return temp == 0?s1.getAge() - s2.getAge():temp;
  9.       }
  10. }

  11. public class HashMapDemo{
  12.        public static void main(String[] args){
  13.              //将学生对象和学生的归属地通过键与值存储到map集合中
  14.             TreeMap<Student,String> tm = new TreeMap<Student,String>(new ComparatorByName());

  15.             tm.put( new Student("lisi" ,38),"北京");
  16.             tm.put( new Student("zhaoliu" ,24),"上海");
  17.             tm.put( new Student("xiaoqiang" ,31),"沈阳");
  18.             tm.put( new Student("wangcai" ,28),"大连");
  19.             tm.put( new Student("zhaoliu" ,24),"铁岭");
  20.             
  21.             Iterator<Map.Entry<Student,String>> it = tm.entrySet().iterator();

  22.              while(it.hasNext()){
  23.                   Map.Entry<Student,String> me = it.next();
  24.                   Student key = me.getKey();
  25.                   String value = me.getValue();
  26.                   System.out.println(key.getName() + ":" + key.getAge() + "---" + value);
  27.             }
  28.       }
  29. }
运行结果:


使用LinkedHashMap则是跟原来存入的顺序是一致的。

示例7:
  1. import java.util.HashMap;
  2. import java.util.Iterator;
  3. import java.util.LinkedHashMap;
  4. import java.util.Map;

  5. public class LinkedHashMapDemo{
  6.        public static void main(String[] args){
  7.             HashMap<Integer,String> hm = new LinkedHashMap<Integer,String>();

  8.             hm.put(7, "zhouqi");
  9.             hm.put(3, "zhangsan");
  10.             hm.put(1, "qianyi");
  11.             hm.put(5, "wangwu");

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

  13.              while(it.hasNext()){
  14.                   Map.Entry<Integer,String> me = it.next();

  15.                   Integer key = me.getKey();
  16.                   String value = me.getValue();

  17.                   System.out. println(key + ":" + value);
  18.             }
  19.       }
  20. }
运行结果:


  练习:
    “fdqavcbsacdfs”获取该字符串中,每一个字母出现的次数。
     要求打印结果是:a(2)b(1)...;


    思路:
    对于结果的分析发现,字母和次数之间存在着映射的关系,而且这种关系很多。
    很多就需要存储,能存储映射关系的容器有数组和Map结合。
    关系中没有编号!那就使用Map结合。
    又发现可以保证唯一性的一方具备着顺序,如a、b、c...
    所以可以使用TreeMap集合。

    这个集合最终应该存储的是字母和次数的对应关系。
    1. 因为操作的是字符串中的字母,所以先将字符串变成字符数组。
    2. 遍历字符数组,用每一个字母作为键去查Map集合这个值。
    如果该字母键不存在,就将该字母作为键,1作为值存储到map集合中。
    如果该字母键存在,就将该字母键对应值取出并+1,再将该字母和+1后的值存储到map集合中。键相同值会覆盖,这样就记录住了该字母的次数。

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


代码:
  1. import java.util.Iterator;
  2. import java.util.Map;
  3. import java.util.TreeMap;

  4. public class MapTest{
  5.        public static void main(String[] args){
  6.             String str = "fdqavcbsacdfs";

  7.             String s = getCharCount(str);

  8.             System.out.println(s);
  9.       }

  10.        public static String getCharCount(String str){
  11.              //将字符串变为字符数组
  12.              char[] chs = str.toCharArray();
  13.             
  14.              //定义map集合表
  15.             Map<Character,Integer> map = new TreeMap<Character,Integer>();
  16.             
  17.              for(int i = 0; i < chs.length; i++){
  18.                    if(!(chs[i] >= 'a' && chs[i] <= 'z' || chs[i] >= 'A' && chs[i] <= 'Z' ))
  19.                          continue;

  20.                    //将数组中的字母作为键去查map表
  21.                   Integer value = map.get(chs[i]);
  22.                   
  23.                    int count = 0;

  24.                    //判断值是否为null
  25.                    if(value!=null){
  26.                         count = value;
  27.                   }
  28.                   count++;

  29.                   map.put(chs[i],count);
  30.             }

  31.              return mapToString(map);
  32.       }

  33.        private static String mapToString(Map<Character,Integer> map){
  34.             StringBuilder sb = new StringBuilder();

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

  36.              while(it.hasNext()){
  37.                   Character key = it.next();
  38.                   Integer value = map.get(key);

  39.                   sb.append(key + "(" + value + ")" );
  40.             }
  41.              return sb.toString();
  42.       }
  43. }
运行结果:


Map在有映射关系时,可以优先考虑,在查表法中的应用较为多见。

示例:
  1. import java.util.HashMap;
  2. import java.util.Map;

  3. public class MapTest{
  4.        public static void main(String[] args){
  5.             String week = getWeek(1);
  6.             System.out.println(week);

  7.             System.out.println(getWeekByMap(week));
  8.       }

  9.        public static String getWeekByMap(String week){
  10.             Map<String,String> map = new HashMap<String,String>();
  11.             
  12.             map.put( "星期一","Mon" );
  13.             map.put( "星期二","Tue" );
  14.             map.put( "星期三","Wes" );
  15.             map.put( "星期日","Sun" );
  16.             map.put( "星期天","Sun" );
  17.             
  18.              return map.get(week);
  19.       }

  20.        public static String getWeek(int week){
  21.              if(week<1 || week>7)
  22.                    throw new RuntimeException("没有对应的星期,请您重新输入" );

  23.             String[] weeks = { "","星期一" ,"星期二" };
  24.       
  25.              return weeks[week];
  26.       }
  27. }
运行结果:


Collections工具类

   Collections:是集合框架的工具类,里面的方法都是静态的。

示例1:
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.List;

  5. public class CollectionsDemo{
  6.        public static void main(String[] args){
  7.              demo1();
  8.       }

  9.        public static void demo1(){
  10.             List<String> list = new ArrayList<String>();

  11.             list.add( "abcde");
  12.             list.add( "cba");
  13.             list.add( "aa");
  14.             list.add( "zzz");
  15.             list.add( "cba");
  16.             list.add( "nbaa");

  17.              //对list集合进行指定顺序的排序
  18.             Collections. sort(list);
  19.             System. out.println(list);

  20.             Collections. sort(list,new ComparatorByLength());
  21.             System. out.println(list);
  22.             
  23.              mySort(list,new ComparatorByLength());
  24.             System. out.println(list);
  25.       }

  26.        public static <T> void mySort(List<T> list,Comparator<? super T> comp){
  27.              for(int i = 0; i < list.size() - 1; i++){
  28.                    for(int j = i + 1; j < list.size(); j++){
  29.                          if(comp.compare(list.get(i),list.get(j))>0){
  30.                               Collections. swap(list ,i,j);
  31.                         }
  32.                   }
  33.             }
  34.       }
  35. }

  36. class ComparatorByLength implements Comparator<String>{
  37.        public int compare(String o1,String o2){
  38.              int temp = o1.length() - o2.length();
  39.              return temp == 0?o1.compareTo(o2):temp;
  40.       }
  41. }
运行结果:


示例2: 
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.List;

  5. public class CollectionsDemo{
  6.        public static void main(String[] args){
  7.             demo2();
  8.       }

  9.        public static void demo2(){
  10.             List<String> list = new ArrayList<String>();

  11.             list.add( "abcde");
  12.             list.add( "cba");
  13.             list.add( "aa");
  14.             list.add( "zzz");
  15.             list.add( "cba");
  16.             list.add( "nbaa");
  17.       
  18.             Collections.sort(list);
  19.             System.out.println(list);

  20.              int index = Collections.binarySearch(list,"aaa");
  21.             System.out.println( "index = " + index);//-2 -index-1

  22.              //获取最大值
  23.             String max = Collections.max(list, new ComparatorByLength());
  24.             System.out.println( "max = " + max);
  25.       }
  26. }

  27. class ComparatorByLength implements Comparator<String>{
  28.        public int compare(String o1,String o2){
  29.              int temp = o1.length() - o2.length();
  30.              return temp == 0?o1.compareTo(o2):temp;
  31.       }
  32. }
 运行结果:


原因分析:


示例3:
  1. import java.util.Collections;
  2. import java.util.Comparator;
  3. import java.util.TreeSet;

  4. public class CollectionsDemo{
  5.        public static void main(String[] args){
  6.             demo3();
  7.       }

  8.        public static void demo3(){
  9.             TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder());

  10.             ts = new TreeSet<String>(Collections.reverseOrder(new ComparatorByLength()));

  11.             ts.add( "abc");
  12.             ts.add( "hahaha");
  13.             ts.add( "zzz");
  14.             ts.add( "aa");
  15.             ts.add( "cba");

  16.             System.out.println(ts);
  17.       }
  18. }

  19. class ComparatorByLength implements Comparator<String>{
  20.     public int compare(String o1,String o2){
  21.           int temp = o1.length() - o2.length();
  22.           return temp == 0?o1.compareTo(o2):temp;
  23.    }
  24. }
运行结果:


示例4:
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.List;

  4. public class CollectionsDemo{
  5.        public static void main(String[] args){
  6.              demo4();
  7.       }

  8.        public static void demo4(){
  9.             List<String> list = new ArrayList<String>();

  10.             list.add( "abcde");
  11.             list.add( "cba");
  12.             list.add( "aa");

  13.             System. out.println(list);
  14.             Collections. replaceAll(list,"cba", "nba");
  15.             System. out.println(list);
  16.       }
  17. }
运行结果:


示例5:
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.List;

  4. public class CollectionsDemo{
  5.        public static void main(String[] args){
  6.              demo5();
  7.       }

  8.        public static void demo5(){
  9.             List<String> list = new ArrayList<String>();

  10.             list.add( "abcde");
  11.             list.add( "cba");
  12.             list.add( "zhangsan");
  13.             list.add( "zhaoliu");
  14.             list.add( "xiaoqiang");

  15.             System. out.println(list);
  16.             Collections. shuffle(list);
  17.             System. out.println(list);
  18.       }
  19. }
运行结果:


原因分析:


0 0
原创粉丝点击