1.遍历HashMap
public class Mmap {
public static void main(String []args){
Map<Integer,String>map = new HashMap<>();
map.put(0,"yzq");
map.put(3,"yxc");
map.put(2,"yxxx");
map.put(1,"yxcv");
System.out.println(map.toString());
//获取键对应的值
System.out.println(map.get(2));
//是否包含某个键
System.out.println(map.containsKey(5));
//删除某个键-值
map.remove(1);
//遍历map
for(Map.Entry<Integer,String>entry:map.entrySet()){
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
2.TreeMap,按键值排序
//按照键升序--使用TreeMap
Map<Integer,String>orderMap = new TreeMap<>(Collections.reverseOrder());
orderMap.putAll(map);
System.out.println(orderMap.toString());
3.练习1–统计字符串每个字符的个数
package bilibili.chapter16;
import java.util.*;
public class StrMap{
public static void main(String[] args) {
Map<String,Integer>strMap = new TreeMap<>();
Scanner sc = new Scanner(System.in);
String str = sc.next();
char []chars = str.toCharArray();
for(char c:chars){
String key = c + "";
if(!strMap.containsKey(key)){
strMap.put(key,1);
}else{
Integer value = strMap.get(key);
value ++;
strMap.put(key,value);
}
}
for(Map.Entry<String,Integer>entry: strMap.entrySet()){
System.out.println(entry.getKey() + " "+entry.getValue());
}
Map<String,Integer>reserveMap = new TreeMap<>(Comparator.reverseOrder());
reserveMap.putAll(strMap);
System.out.println("反序后");
for(Map.Entry<String,Integer>entry: reserveMap.entrySet()){
System.out.println(entry.getKey() + " "+entry.getValue());
}
}
}
4.练习2–斗地主
package bilibili.chapter16;
import java.util.*;
public class JQKMap {
public static void main(String[] args) {
String []colors = "♠-♥-♣-♦".split("-");
String []numbers = "2-3-4-5-6-7-8-9-10-J-Q-K-A".split("-");
HashMap<Integer,String>pokers = new HashMap<>();
ArrayList<Integer>list = new ArrayList<>();
list.add(0);
list.add(1);
pokers.put(0,"大王");
pokers.put(1,"小王");
int key = 2;
for(String number:numbers){
for(String color:colors){
String p = color + number;
pokers.put(key,p);
list.add(key);
key++;
}
}
System.out.println(pokers);
Collections.shuffle(list);
ArrayList<Integer>dipai = new ArrayList<>();
ArrayList<Integer>p1 = new ArrayList<>();
ArrayList<Integer>p2 = new ArrayList<>();
ArrayList<Integer>p3 = new ArrayList<>();
for(int i=0;i<list.size();i++){
Integer poker = list.get(i);
if(i>51){
dipai.add(poker);
}else if(i%3==0){
p1.add(poker);
}else if(i%3==1){
p2.add(poker);
}else {
p3.add(poker);
}
}
Collections.sort(dipai);
Collections.sort(p1);
Collections.sort(p2);
Collections.sort(p3);
look("底牌",dipai,pokers);
look("第一个人",p1,pokers);
look("第二个人",p2,pokers);
look("第三个人",p3,pokers);
}
private static void look(String name,ArrayList<Integer> list,HashMap<Integer,String>map){
System.out.println(name+"的牌:");
for(Integer poker:list){
System.out.print(map.get(poker)+" ");
}
System.out.println();
}
}