【java】HashMap、Map、Set、HashMap.put()、HashMap.keySet()、HashMap.entrySet()、Map.Entry内部类

时间:2023-12-15 08:34:38
 package com.tn.hashMap;

 public class Student {
private String id;
private String name;
public Student(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}

Student

 package com.tn.hashMap;

 import java.util.HashMap;
import java.util.Map;
import java.util.Set; public class HashMapDemo {
public static void main(String[] args){
Student student1=new Student("0001","哪吒");
Student student2=new Student("0002","杨戬");
Student student3=new Student("0003","雷震子");
HashMap<String,Student> hm=new HashMap<String,Student>();
//HashMap的键值对都是Object类型,如果需要用到基本类型可用Integer之类的包装类
hm.put(student1.getId(), student1);
hm.put(student2.getId(), student2);
hm.put(student3.getId(), student3);
//put方法如果key相同,则后面的value会覆盖前面的
System.out.println(hm.size());
System.out.println(hm); //通过keySet方法用Set遍历
Set<String> set=hm.keySet();
for(String str:set){
System.out.println(hm.get(str));//打印出来的顺序是不可预知的
} //通过entrySet方法用set遍历
/*放入HashMap集合中的key、Value会被包装成Map.Entry内部类的属性
* 一个键值对成为一个Map.Entry实例对象
*
*/
Set<Map.Entry<String, Student>> set1=hm.entrySet();
//Set<Map<K,V>.Entry<K, V>> 注:Map后的泛型可不指明,不用写。
for(Map.Entry<String, Student> mEntry:set1){
System.out.println(mEntry.getKey()+":"+mEntry.getValue());
}
}
}

HashMapDemo


通过HashMap计算字符串中各字母出现次数:

 String str="abbcccddddeeeeeffffff";
HashMap<String,Integer> hashMap=new HashMap<String,Integer>();
for(int i=0;i<str.length();i++){
if(!hashMap.containsKey(str.substring(i, i+1))){
hashMap.put(str.substring(i, i+1), 1);
}else{
hashMap.put(str.substring(i,i+1), hashMap.get(str.substring(i, i+1))+1);
}
}
System.out.println(hashMap);

snippet