hashmap的小应用---投票去旅游

发布时间 2023-11-07 19:49:41作者: 0927#$

在学习了map之后,使用简单的hashmap进行简单的全班同学投票旅游地点

package com.itheima.myMap;

import java.util.*;
import java.util.function.BiConsumer;

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


//模拟投票
Random ra = new Random();
String[] arr = {"A", "B", "C", "D"};
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 80; i++) {
list.add(arr[ra.nextInt(arr.length)]);

}
//System.out.println(list);
//对ABCD进行投票
HashMap<String, Integer> hm = new HashMap<>();
for (String s : list) {
if (hm.containsKey(s)) {
Integer i = hm.get(s);
i++;
hm.put(s, i);
} else {
hm.put(s, 1);
}
}
//hm.forEach((str,i)-> System.out.println(str+"="+i));
System.out.println(hm);


//找最大值
int max = 0;
Set<Map.Entry<String, Integer>> entries = hm.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
Integer count = entry.getValue();
if (max < count) {
max = count;
}
}
System.out.println(max);

//对数量为最大值的进行打印

for (Map.Entry<String, Integer> entry : entries) {
Integer count = entry.getValue();
if (max == count) {
System.out.println(entry.getKey());
}
}


}


}