【java】HashMap、Map、Set、HashMap.put()、HashMap.keySet()、HashMap.entrySet()、Map.Entry内部类
2024-08-29 23:28:21
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
最新文章
- XML Schema and XMLspy notes
- Topcoder SRM570 900 CurvyonRails
- JS-Dom概念
- OC之0801
- [转] 国内外最全面和主流的JS框架与WEB UI库(强烈推荐)
- JavaScript 同源策略
- 经常被忽略的几个CSS3属性之强大应用(一、timing-function: steps() 二、animation-direction 三、timing-function: cubic-bezier())
- APK签名校验绕过
- c语言全局变量与局部变量(当变量重名时)的使用情况
- <;微信应用开发系列>;定时刷新AccessToken
- ubuntu12.04安装openjdk-7
- SpringBoot 整合 Swagger2
- 《Spring Cloud与Docker微服务架构实战》配套代码
- C#中关键字 &#39;User&#39; 附近有语法错误
- mysq带条件的分页查询数据结果错误
- 20175224 2018-2019-2 《Java程序设计》第七周学习总结
- asp.net core2.0中网站发布的时候,怎么样才配置才可以使视图文件不被打包进去?
- java基础篇---HTTP协议
- 2018.12.30 poj3734 Blocks(生成函数)
- mormot中间件成功匹配客户端FDMemTable和ClientDataSet