Java 中集合框架(2)---Map极其子类

来源:互联网 发布:欧文16年总决赛数据 编辑:程序博客网 时间:2024/06/06 03:04

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

共性方法:1,添加。
                        put(K key, V value)   添加元素 如果出现添加时出现相同的键。那么后添加的值会覆盖原有键对应值, 并put方法会返回被覆盖的值。如果是第一次添加则返回的是null
                        putAll(Map<? extends K,? extends V> m)

                    2,删除。
                       clear()
                       remove(Object key)

                   3,判断。
                       containsValue(Object value)
                       containsKey(Object key)
                       isEmpty()


                   4,获取。
                       get(Object key)
                       size()
                      values()  返回  Collection<V>

                      entrySet()  返回  Set<Map.Entry<K,V>>
                      keySet()  返回  Set<K>

Map
    |--Hashtable:底层是哈希表数据结构,不可以存入null键null值。该集合是线程同步的。效率低。
    |--HashMap:底层是哈希表数据结构,允许使用 null 值和 null 键,该集合是不同步的。将hashtable替代 效率高。
    |--TreeMap:底层是二叉树数据结构。线程不同步。可以用于给map集合中的键进行排序。
Map 和 Set表面上看很像。其实,Set底层就是使用了Map集合。

map集合的两种取出方式:
1,Set<k>  keySet():将map中所有的键存入到Set集合。因为set具备迭代器。
所有可以迭代方式取出所有的键,在根据get方法。获取每一个键对应的值。
事例:

               //先获取map集合的所有键的Set集合,keySet() <>内是键的类型此处是String;
Set<String> keySet = map.keySet();
//有了Set集合。就可以获取其迭代器。
Iterator<String> it = keySet.iterator();
while(it.hasNext())
{
String key = it.next();
//有了键可以通过map集合的get方法获取其对应的值。
String value  = map.get(key);
System.out.println("key:"+key+",value:"+value);
}


2,Set<Map.Entry<k,v>> entrySet():将map集合中的映射关系存入到了set集合中,
而这个关系的数据类型就是:Map.Entry。Entry其实就是Map中的一个static内部接口。之所以定义在内部是因为只有有了Map集合,有了键值对,才会有键值                                 的映射关系。关系属于Map集合中的一个内部事物。而且该事物在直接访问Map集合中的元素。

                               事例:

                               //将Map集合中的映射关系取出。存入到Set集合中。Set集合的泛型是Map.Entry类型 Map.Entry的泛型是map的泛型,即键的类型和值的类型
              Set<Map.Entry<String,String>> entrySet = map.entrySet();
              Iterator<Map.Entry<String,String>> it = entrySet.iterator();
                     while(it.hasNext())
                 {
      Map.Entry<String,String> me = it.next();
      String key = me.getKey();
      String value = me.getValue();
      System.out.println(key+":"+value);
                    }

练习:每一个学生都有对应的归属地。学生Student,地址String。学生属性:姓名,年龄。注意:姓名和年龄相同的视为同一个学生。保证学生的唯一性。
注意:在往hashMap存入数据是键的对象要重新hashCode和equles方法
class Student implements Comparable<Student>
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
//让student先具备了自然顺序 先按年龄排序 再按姓名排序
public int compareTo(Student s)
{
int num = new Integer(this.age).compareTo(new Integer(s.age));


if(num==0)
return this.name.compareTo(s.name);
return num;
}

       //作为键要存入HashMap就要重写 hashCode(),equals(Object obj)这两个方法
public int hashCode()
{
return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");


Student s = (Student)obj;


return this.name.equals(s.name) && this.age==s.age;

}

public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+":"+age;
}
}

class  MapTest
{
public static void main(String[] args) 
{
HashMap<Student,String> hm = new HashMap<Student,String>();


hm.put(new Student("lisi1",21),"beijing");
hm.put(new Student("lisi1",21),"tianjin");
hm.put(new Student("lisi2",22),"shanghai");
hm.put(new Student("lisi3",23),"nanjing");
hm.put(new Student("lisi4",24),"wuhan");
//第一种取出方式 keySet

Set<Student> keySet = hm.keySet();
Iterator<Student> it = keySet.iterator();
while(it.hasNext())
{
Student stu = it.next();
String addr = hm.get(stu);
System.out.println(stu+".."+addr);
}

//第二种取出方式 entrySet
Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student,String>> iter = entrySet.iterator();
while(iter.hasNext())
{
Map.Entry<Student,String> me = iter.next();
Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu+"........."+addr);
}
}
}

练习:学生对象的姓名进行升序排序。

因为数据是以键值对形式存在的。

所以要使用可以排序的Map集合。TreeMap。

注意:之前的Student 因为实现了 Comparable<Student>  重写了compareTo(Student s)  具备了自然顺序 这个顺序是先按年龄排序与我们的需求不符合,因此需要比较器

           实现Comparator<Student> 重写 compare(Student s1,Student s2)

class StuNameComparator implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
int num = s1.getName().compareTo(s2.getName());
if(num==0)
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));


return num;
}
}

class  MapTest2
{
public static void main(String[] args) 
{

//放到TreeMap中 具备顺序
TreeMap<Student,String> tm = new TreeMap<Student,String>(new StuNameComparator());
tm.put(new Student("blisi3",23),"nanjing");
tm.put(new Student("lisi1",21),"beijing");
tm.put(new Student("alisi4",24),"wuhan");
tm.put(new Student("lisi1",21),"tianjin");
tm.put(new Student("lisi2",22),"shanghai");

Set<Map.Entry<Student,String>> entrySet = tm.entrySet();
Iterator<Map.Entry<Student,String>> it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Student,String> me = it.next();


Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu+":::"+addr);
}
}
}

练习:"sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数。希望打印结果:a(1)c(2).....
             通过结果发现,每一个字母都有对应的次数。说明字母和次数之间都有映射关系。当发现有映射关系时,可以选择map集合。因为map集合中存放就是映射关系。

思路:
1,将字符串转换成字符数组。因为要对每一个字母进行操作。
2,定义一个map集合,因为打印结果的字母有顺序,所以使用treemap集合。
3,遍历字符数组。
将每一个字母作为键去查map集合。
如果返回null,将该字母和1存入到map集合中。
如果返回不是null,说明该字母在map集合已经存在并有对应次数。
那么就获取该次数并进行自增。,然后将该字母和自增后的次数存入到map集合中。覆盖调用原理键所对应的值。
4,将map集合中的数据变成指定的字符串形式返回。

事例:

class  MapTest3
{
public static void main(String[] args) 
{
String s= charCount("ak+abAf1c,dCkaAbc-defa");
System.out.println(s);
}

public static String charCount(String str)
{
char[] chs = str.toCharArray();

//泛型里面是应用类型,不能写基本数据类型,Character并且实现了Comparable
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
int count = 0;
for(int x=0; x<chs.length; x++)
{
if(!(chs[x]>='a' && chs[x]<='z' || chs[x]>='A' && chs[x]<='Z'))
continue;
Integer value = tm.get(chs[x]);
if(value!=null)
count = value;
count++;
tm.put(chs[x],count);//直接往集合中存储字符和数字,为什么可以,因为自动装箱。
count = 0;
/*
if(value==null)
{
tm.put(chs[x],1);
}
else
{
value = value + 1;
tm.put(chs[x],value);
}
*/

}

StringBuilder sb = new StringBuilder();
Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
Iterator<Map.Entry<Character,Integer>>  it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Character,Integer> me = it.next();
Character ch = me.getKey();
Integer value = me.getValue();
sb.append(ch+"("+value+")");
}
return sb.toString();
}


}

1 0