HashMap:无序,不重复,无索引
HashMap小练习:
import java.text.ParseException;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import static java.lang.Math.abs;
public class Test3 {
public static void main(String[] args) {
//定义数组,存储4个景点
String[] arr={"A","B","C","D"};
ArrayList<String> list=new ArrayList<>();
Random r=new Random();
for (int i = 0; i < 80; i++) {
int i1 = r.nextInt(arr.length);
list.add(arr[i1]);
}
HashMap<String,Integer> hashMap=new HashMap<>();
for (String name : list) {
//判断当前投票的景点是否存在
if(hashMap.containsKey(name)){
//存在
int count = hashMap.get(name);
count++;
hashMap.put(name,count);
}else {//不存在
hashMap.put(name,1);
}
}
//求最大值
int max=0;
Set<Map.Entry<String, Integer>> entries = hashMap.entrySet();
//判断哪个景点的次数跟最大值一样,如果一样,打印出来
for (Map.Entry<String, Integer> entry : entries) {
int count = entry.getValue();
if(count>max){
max=count;
}
}
System.out.println(max);
}
}