Java中关于HashMap的使用和遍历
1:使用HashMap的一个简单例子
- package com.pb.collection;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Set;
- import java.util.Map.Entry;
- public class HashMapDemo {
- public static void main(String[] args) {
- HashMap<String, String> hashMap = new HashMap<String, String>();
- hashMap.put("cn", "中国");
- hashMap.put("jp", "日本");
- hashMap.put("fr", "法国");
- System.out.println(hashMap);
- System.out.println("cn:" + hashMap.get("cn"));
- System.out.println(hashMap.containsKey("cn"));
- System.out.println(hashMap.keySet());
- System.out.println(hashMap.isEmpty());
- hashMap.remove("cn");
- System.out.println(hashMap.containsKey("cn"));
- //采用Iterator遍历HashMap
- Iterator it = hashMap.keySet().iterator();
- while(it.hasNext()) {
- String key = (String)it.next();
- System.out.println("key:" + key);
- System.out.println("value:" + hashMap.get(key));
- }
- //遍历HashMap的另一个方法
- Set<Entry<String, String>> sets = hashMap.entrySet();
- for(Entry<String, String> entry : sets) {
- System.out.print(entry.getKey() + ", ");
- System.out.println(entry.getValue());
- }
- }
- }
2:一个结合List和HashMap实现的例子
- import java.util.Iterator;
- import java.util.List;
- import java.util.HashMap;
- import java.util.ArrayList;
- import java.util.Map;
- import java.util.Scanner;
- import java.util.Set;
- import java.util.Map.Entry;
- /**
- * 在不创建学生类的情况下,从键盘输入n个学生信息(学号,姓名,年龄),
- * 输入完成后,打印出各个学生信息
- * @author ccna_zhang
- *
- */
- public class Assignment {
- public static void main(String[] args) {
- //定义保存学生信息的List,元素类型为HashMap
- List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
- Scanner input = new Scanner(System.in);
- System.out.println("请输入学生的信息,y表示继续,n表示退出");
- while("y".equals(input.next())) {
- HashMap<String, Object> map = new HashMap<String, Object>();
- System.out.println("请输入学号");
- map.put("studentno", input.next());
- System.out.println("请输入姓名");
- map.put("name", input.next());
- System.out.println("请输入年龄");
- map.put("age", input.nextInt());
- list.add(map);
- System.out.println("请继续输入学生的信息,y表示继续,n表示退出");
- }
- System.out.println("输入的学生信息为:");
- System.out.println("学生数量为:" + list.size());
- Iterator<HashMap<String, Object>> it = list.iterator();
- int i = 1;
- while(it.hasNext()) {
- HashMap<String, Object> stuMap = it.next();
- System.out.print("第" + i + "个学生的信息为");
- System.out.println("学号:" + stuMap.get("studentno") + " ,姓名:" + stuMap.get("name") + " ,年龄:" + stuMap.get("age"));
- }
- }
- }