1 package com.tn.hashMap; 2 3 public class Student { 4 private String id; 5 private String name; 6 public Student(String id, String name) { 7 super(); 8 this.id = id; 9 this.name = name; 10 } 11 public String getId() { 12 return id; 13 } 14 public void setId(String id) { 15 this.id = id; 16 } 17 public String getName() { 18 return name; 19 } 20 public void setName(String name) { 21 this.name = name; 22 } 23 @Override 24 public String toString() { 25 return name; 26 } 27 }
1 package com.tn.hashMap; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 import java.util.Set; 6 7 public class HashMapDemo { 8 public static void main(String[] args){ 9 Student student1=new Student("0001","哪吒"); 10 Student student2=new Student("0002","杨戬"); 11 Student student3=new Student("0003","雷震子"); 12 HashMap<String,Student> hm=new HashMap<String,Student>(); 13 //HashMap的键值对都是Object类型,如果需要用到基本类型可用Integer之类的包装类 14 hm.put(student1.getId(), student1); 15 hm.put(student2.getId(), student2); 16 hm.put(student3.getId(), student3); 17 //put方法如果key相同,则后面的value会覆盖前面的 18 System.out.println(hm.size()); 19 System.out.println(hm); 20 21 //通过keySet方法用Set遍历 22 Set<String> set=hm.keySet(); 23 for(String str:set){ 24 System.out.println(hm.get(str));//打印出来的顺序是不可预知的 25 } 26 27 //通过entrySet方法用set遍历 28 /*放入HashMap集合中的key、Value会被包装成Map.Entry内部类的属性 29 * 一个键值对成为一个Map.Entry实例对象 30 * 31 */ 32 Set<Map.Entry<String, Student>> set1=hm.entrySet(); 33 //Set<Map<K,V>.Entry<K, V>> 注:Map后的泛型可不指明,不用写。 34 for(Map.Entry<String, Student> mEntry:set1){ 35 System.out.println(mEntry.getKey()+":"+mEntry.getValue()); 36 } 37 } 38 }
通过HashMap计算字符串中各字母出现次数:
1 String str="abbcccddddeeeeeffffff"; 2 HashMap<String,Integer> hashMap=new HashMap<String,Integer>(); 3 for(int i=0;i<str.length();i++){ 4 if(!hashMap.containsKey(str.substring(i, i+1))){ 5 hashMap.put(str.substring(i, i+1), 1); 6 }else{ 7 hashMap.put(str.substring(i,i+1), hashMap.get(str.substring(i, i+1))+1); 8 } 9 } 10 System.out.println(hashMap);