HashMap
Map集合的实现类一:HashMap
package com.heima.map1;
import java.lang.reflect.Array;
import java.util.*;
//80人随机在4个地方选出一个,并统计那个地方备选的最多
public class HashMapDemo02 {
public static void main(String[] args) {
//集中数组定义方法
String arr[]={"a","b","c","d"};
String[]a1=new String[5];
String[]b=new String[]{"",""};
String c[]={""};
List<String> list=new ArrayList<>();//List是一个接口,ArrayList是他的实现类,不能使用List创建对象,使用List作为对象的引用
Random r=new Random();//得到随机数
//给每个人分配要去的地方
for (int i = 0; i < 80; i++) {
int mude=r.nextInt(4);//得到每个人要去的地方在arr数组中的索引,得到的随机数为0,1,2,3
list.add(arr[mude]);//通过索引得到每个人要去的地方
}//分配完成,存储到了list列表中
System.out.println(list);
//统计四个目的地被选择的次数
HashMap<String,Integer>hm=new HashMap<>();//Map集合判断是否存在键
for (String s : list) {//list.for,对每个list集合中的目的地,判断
//Map集合已存在键s,Integer+1,
if(hm.containsKey(s)){
int a=hm.get(s);//用HashMap对象的get()方法获得键s对应的值并放到a中
a++;//目的地出现的次数加一
hm.put(s,a);//把目的地s和次数a放入HashMap集合,put方法引入新的已经存在的键时,新的值会覆盖旧的
}
//不存在键s则
else{
hm.put(s,1);
}
}
System.out.println(hm);
int max=0;
//HashMap的entrySet方法得到HashMap集合存储的每个键值对对象,通过键值对对象可以使用getKey()和getValue()方法
Set<Map.Entry<String, Integer>> entries = hm.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
Integer value = entry.getValue();
if (value>max){
max=value;
}
}
System.out.println(max);
//判断那个地点最多人
for (Map.Entry<String, Integer> entry : entries) {
if (entry.getValue()==max){
System.out.println(entry.getKey());
}
}
//遍历map集合
/*Set<String> jian = hm.keySet();
for (String s : jian) {
Integer value = hm.get(s);
}*/
}
}