hashmap知识点

来源:互联网 发布:类似于dropbox的软件 编辑:程序博客网 时间:2024/06/05 05:42

import java.util.Collection;

import java.util.HashMap;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

//@auther
//@version
public class map {
  public static void main(String[] args) {
 //使用map存放每个人的姓名和年龄
Map<String, Integer> map= new HashMap<String , Integer>();
map.put("张娜", 18);
map.put("李四", 20);
map.put("王五", 22);
map.put("李四", 21);
map.put("王五", 26);
map.put("王五", 32);
System.out.println(map.size());
//根据key的值获取李四的年龄
int age= map.get("李四");
System.out.println(age);
System.out.println(map.containsKey("王五"));
//遍历集合中所有的元素方法
//方式一 遍历所有的key
  Set<String> set= map.keySet();
  for(String key:set){
System.out.println(key+":"+map.get(key));
  }


//方式二遍历所有的value
Collection<Integer> c= map.values();
for(Integer a:c){
System.out.println(a+"--------------");
}


//方式三遍历所有的键值对entry
Set<Entry<String,Integer>>en= map.entrySet();
 for(Entry<String,Integer> s:en){
 String key=s.getKey();
 int value = s.getValue();
 System.out.println(key+":"+value);
 }
}

}