Map集合(接口)
1.Map集合的概述:
将键映射到值的对象,一个映射不能包含重复的键,每个键最多只能映射到一个值
2.格式:Map<K , V>
K——键的类型
V——映射的值的类型
3.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(): 返回一个键值对的Set集合
V get(Object key):根据键获取值
Set<K> keySet():获取集合中所有键的集合
Collection<V> values():获取集合中所有值的集合
(5)长度功能
int size():返回集合中的键值对的对数
HashMap集合(Map集合的子实现类)
1.注:(1)HashMap集合允许插入null值和null键
(2)采用put方法放置数据,第一次放置时返回的是null,第二次放置键相同的数据会返回上一次的值
例:
import java.util.HashMap;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String, String> hm = new HashMap<String, String>();
String str = hm.put("9","卡萨诺");
String str1 = hm.put("9","巴洛特利");
System.out.println(str);
System.out.println(str1);
}
}
(3)Map集合的数据结构只和键有关
(4)键相同,值覆盖(被最后一个覆盖)
(5)键为对象时,需重写hashCode() 和 equals() 方法
2.Map集合的三种遍历方法
:
(1)keySet() (返回为Set<K>) 和get(key)(返回的为值)方法
例:
import java.util.HashMap;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<Football, Integer> hm = new HashMap<Football, Integer>();
hm.put(new Football("卡萨诺",31),9);
hm.put(new Football("巴洛特利",26),45);
hm.put(new Football("伊莫比莱",28),11);
Set<Football> set = hm.keySet();
for(Football f:set) {
System.out.println(f);
}
}
}
class Football{
String name;
int age;
public Football(){
}
public Football(String name, int age) {
super();
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;
}
//重写toString()方法
public String toString(){
return name+","+age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Football other = (Football) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
注:需导包到 java.util.Map.Entry
例:
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
public class HashMap1 {
public static void main(String[] args) {
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1,"卡萨诺");
hm.put(2,"巴洛特利");
hm.put(3,"因扎吉");
Set<Entry<Integer,String>> set = hm.entrySet();
for(Entry<Integer,String> en:set) {
System.out.println(en.getKey()+","+en.getValue());
}
}
}
例:
import java.util.HashMap;
import java.util.Collection;
public class HashMap1 {
public static void main(String[] args) {
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1,"卡萨诺");
hm.put(2,"巴洛特利");
hm.put(3,"因扎吉");
Collection<String> values = hm.values();
for(String valu:values) {
System.out.println(valu);
}
}
}
LinkedHashMap集合(HashMap的子类)
1.概述:Map 接口的哈希表和链接列表实现,具有可预知的迭代顺序
2.特点:底层的数据结构是链表和哈希表 元素有序 并且唯一
存取和取出一致
注:元素的有序性由链表数据结构保证 唯一性由 哈希表数据结构保证
TreeMap集合(Map集合子实现类)
1.特点:元素唯一,且可对元素进行排序(自然排序,比较器排序)
TreeMap集合底层为红黑树结构,可以保证元素的唯一性并且可对元素进行排序
2. 注:TreeMap集合允许插入null值,不允许插入null键
(1)自然排序:该类需实现Comparable接口,重写compareTo() 方法(同TreeSet集合)
(2)比较器排序:重写Comparator接口中的public int compare(T o1 , T o2) 方法 (同TreeSet集合)
例1:(自然排序)
import java.util.TreeMap;
import java.util.Set;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<Football, Integer> tm = new TreeMap<Football, Integer>();
tm.put(new Football("卡萨诺", 31), 9);
tm.put(new Football("巴洛特利", 31), 45);
tm.put(new Football("伊莫比莱", 28), 11);
Set<Football> set = tm.keySet();
for (Football f : set) {
System.out.println(f);
}
}
}
class Football implements Comparable<Football> {
String name;
int age;
public Football() {
}
public Football(String name, int age) {
super();
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;
}
// 重写toString()方法
public String toString() {
return name + "," + age;
}
public int compareTo(Football f) {
int num = this.age - f.age;
int num1 = num == 0 ? this.getName().length() - f.getName().length() : num;
int num2 = num1 == 0 ? this.getName().compareTo(f.getName()) : num1;
return num2;
}
}
例2:(比较器排序)
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.Comparator;
import java.util.Set;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<Football, Integer> tm = new TreeMap<Football, Integer>(new Comparator<Football>() {
@Override
public int compare(Football f1, Football f2) {
int num = f1.getAge() - f2.getAge();
int num1 = num == 0 ? f1.getName().length() - f2.getName().length() : num;
int num2 = num1 == 0 ? f1.getName().compareTo(f2.getName()) : num1;
return num2;
}
});
tm.put(new Football("saneidi", 19), 9);
tm.put(new Football("javier", 21), 45);
tm.put(new Football("zanetti", 21), 11);
Set<Entry<Football,Integer>> set = tm.entrySet();
for (Entry<Football,Integer> en : set) {
System.out.println(en.getKey()+"-----"+en.getValue());
}
}
}
class Football {
String name;
int age;
public Football() {
}
public Football(String name, int age) {
super();
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;
}
// 重写toString()方法
public String toString() {
return name + "," + age;
}
}
课堂练习
import java.util.TreeMap;
import java.util.Scanner;
import java.util.Set;
/*
* 需求:用户随便输入一段字符串,统计字符串中每个字符出现的次数
* 以如此的形式输出:a(5)b(4)c(3)d(2)e(1)
* */
public class MapTest {
public static void main(String[] args) {
//创建HashMap集合来储存
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
//创建键盘录入对象
Scanner sc = new Scanner(System.in);
System.out.println("请输入一段字符串:");
String str = sc.nextLine();
//将字符串转成字符数组
char [] chs = str.toCharArray();
//遍历数组
for(char key:chs) {
//先获取这个键对应的值,若为第一次获取,则取出的值为null
Integer value = tm.get(key);
if(value == null) {
tm.put(key,1);
}
else {
value++;
tm.put(key,value); //键相同,值可以覆盖
}
}
//遍历集合输出
Set<Character> keyset = tm.keySet();
StringBuilder sb = new StringBuilder();
for(Character ch:keyset) {
sb.append(ch).append("(").append(tm.get(ch)).append(")");
}
System.out.println(sb.toString());
}
}