HashMap
public class HashMapTest1 {
public static void main(String[] args) {
//创建对象
//年龄,名字相同认为是同一个人(要重写hashCode和equals方法)
HashMap<Student,String> hm=new HashMap<>();
Student s1=new Student("zhangsan",23);
Student s2=new Student("lisi",24);
Student s3=new Student("wangwu",25);
Student s4=new Student("wangwu",25);
hm.put(s1,"北京");
hm.put(s2,"上海");
hm.put(s3,"广州");
hm.put(s4,"深圳");
//键值对
Set<Map.Entry<Student, String>> set = hm.entrySet();
for(Map.Entry<Student, String> entry:set){
System.out.println(entry.getKey()+"--"+entry.getValue());
}
System.out.println("------------------");
//lambda
hm.forEach((key, Value)-> System.out.println(key+"--"+Value));
System.out.println("------------------");
//键找值
Set<Student> set1 = hm.keySet();
Iterator<Student> it=set1.iterator();
while(it.hasNext()){
Student key = it.next();
System.out.println(key+"--"+hm.get(key));
}
}
}
--------------------------
public class HashMapTest2 {
public static void main(String[] args) {
/*
练习:八十个学生给四个景点投票,统计每个景点的得票情况
*/
//如果要统计的东西较多,可以使用计数器思想
//创建一个数组来存放投票的对象
String []arr={"A","B","C","D"};
//创建一个集合来存放投票结果
ArrayList<String> list=new ArrayList<>();
Random r=new Random();
for(int i=0;i<80;i++){
int index = r.nextInt(arr.length);
list.add(arr[index]);
}
//创建hashmap集合来存放每个元素的个数
HashMap<String,Integer> map=new HashMap<>();
//遍历list集合来统计票数
for (String s : list) {
if(!map.containsKey(s)){
map.put(s,1);
}else{
int count=map.get(s);
count++;
map.put(s,count);
}
}
//打印结果
map.forEach((key,value)-> System.out.println(key+"景点的票数为:"+value));
//求最大值
int max=0;
Set<String> set1 = map.keySet();
for (String s : set1) {
if(map.get(s)>max){
max=map.get(s);
}
}
System.out.println("最大值为:"+max);
//得到最大值的景点
for (String s : set1) {
int count=map.get(s);
if(count==max){
System.out.println(s+"景点的票数为:"+count);
}
}
//上方两步不能合在一起
}
}
----------------------------------------------
public class LinkedHashMapDemo1 {
public static void main(String[] args) {
//有序,不重复,无索引
//底层是哈希表+双向链表
//1.创建集合
LinkedHashMap<String,Integer> lhp=new LinkedHashMap<>();
//2.添加元素
lhp.put("xiangxiang",1);
lhp.put("haha",2);
lhp.put("baby",3);
lhp.put("baby",4);
//打印结果
System.out.println(lhp);//{xiangxiang=1, haha=2, baby=4}
}
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Hexo!