Map集合概述
Interface Map <K,V>:K表示键的类型,V:表示值的类型 Map就是将键映射到值的对象:不能包含重复的键;每个键可以映射到最多一个值
Map的基本方法
Map<String, String> map = new HashMap<>();
map.put("JYQ","XKA");
map.put("WST","DBD");
map.put("WYX","XKA");
map.put("WYX","XBB");
System.out.println(map);
System.out.println(map.remove("JYQ"));
System.out.println(map.remove("JYQ"));
System.out.println(map.containsKey("WST"));
System.out.println(map.containsKey("XZZ"));
System.out.println(map.containsValue("DBD"));
System.out.println(map.containsValue("ZZ"));
System.out.println(map.isEmpty());
System.out.println(map.size());
结果:
{JYQ=XKA, WYX=XBB, WST=DBD}
XKA
null
true
false
true
false
false
2
ArrayList嵌套Map
检查字符串中字符出现次数
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String line = sc.nextLine();
TreeMap<Character,Integer> hm = new TreeMap<>();
for(int i = 0;i<line.length();i++){
char key = line.charAt(i);
Integer value = hm .get(key);
if(value == null){
hm.put(key,1);
} else {
value++;
hm.put(key,value);
}
}
StringBuilder sb = new StringBuilder();
Set<Character> keySet = hm.keySet();
for(Character c : keySet){
Integer value = hm.get(c);
sb.append(c).append("(").append(value).append(")");
}
String result = sb.toString();
System.out.println(result);
|