1 Map集合
(1)Interface Map<K,V> K:键的类型;V:值的类型
将键映射到值的对象,不能包含重复的键,每个键映射一个值(键值对)
(2)Map集合常见方法
V put(K key,V value) 添加,当key相同时,后加的值会覆盖前面的值
Vremove(Object key) 删除
boolean containsKey(Object key) 判断
boolean containsValue(Object value) 判断
boolean isEmpty() 判断
int size() 集合的长度
V get(Object key) 根据键获取值
Set<K> keySet() 获取所有键的集合
Collection<V> values() 获取所有值的集合
Set<Map.Entry<K,V>>entrySet() 获取所有键值对对象的集合
(3)遍历Map集合
示例:
Map<String, String> couples = new HashMap<String, String>();
couples.put("胡斐", "袁紫衣");
couples.put("狄云", "水笙");
couples.put("萧峰", "阿竹");
couples.put("段誉", "王语嫣");
couples.put("虚竹", "西夏公主");
couples.put("郭靖", "黄蓉");
couples.put("韦小宝","阿珂");
//key相同时,会覆盖
couples.put("韦小宝", "双儿");
//遍历Map集合方法一
Set<String> keySet = couples.keySet();
for(String key:keySet){
System.out.println(key + " - " + couples.get(key));
}
System.out.println("------分隔------");
//遍历Map集合方法二
Set<Map.Entry<String, String>> entrySet = couples.entrySet();
for (Map.Entry<String, String> couple : entrySet) {
System.out.println(couple.getKey() + " - " + couple.getValue());
}
(4)当Map中键的数据类型为对象时,需要在类中重写hashCode()和equals()方法,以确保键值的唯一性
Alt+Insert自动生成即可
2 集合嵌套
示例:
ArrayList<HashMap<String, String>> coupleList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> goodCouples = new HashMap<String, String>();
goodCouples.put("郭靖", "黄蓉");
goodCouples.put("令狐冲", "任盈盈");
goodCouples.put("杨过", "小龙女");
coupleList.add(goodCouples);
HashMap<String, String> costarCouples = new HashMap<String, String>();
costarCouples.put("杨康", "穆念慈");
costarCouples.put("林平之", "岳灵珊");
costarCouples.put("公孙止", "裘千尺");
coupleList.add(costarCouples);
for (HashMap<String, String> couples : coupleList) {
for (String key : couples.keySet()) {
System.out.println(key + " - " + couples.get(key));
}
}
3 HashMap或TreeMap应用示例:
import java.util.HashMap;
import java.util.Scanner;
import java.util.TreeMap;
public class MapDemo {
public static void main(String[] args) {
//实现统计字符串中每个字符的个数
System.out.println("请输入一个字符串:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
TreeMap<Character, Integer> targetMap = new TreeMap<Character, Integer>();
//HashMap<Character, Integer> targetMap = new HashMap<Character, Integer>();
for (int i = 0; i < str.length(); i++) {
Character key = str.charAt(i);
Integer value = targetMap.get(key);
if(value == null){
targetMap.put(key,1);
}else{
value++;
targetMap.put(key,value);
}
}
StringBuilder sb = new StringBuilder();
for(Character ch: targetMap.keySet()){
sb.append(ch).append(targetMap.get(ch)).append("\t");
}
System.out.println(sb.toString());
}
}