package test;
import java.util.*;
import java.util.Map.Entry;
import org.junit.Test;
public class MapTest {
@Test
public void testMap() {
Student xiaoqiang = new Student("小强", "男", 10);
Student xiaoLi = new Student("小丽", "女", 14);
Student xiaoMing = new Student("小明", "男", 16);
Student xiaoHong = new Student("小红", "女", 13);
Map map = new HashMap<>();
map.put("xiaoqiang", xiaoqiang);
map.put("xiaoLi", xiaoLi);
map.put("xiaoMing", xiaoMing);
map.put("xiaoHong", xiaoHong);
System.out.println("===========使用keySet============");
for (String key : map.keySet()) {
System.out.println("key:" + key);
Student value = https://www.it610.com/article/map.get(key);
String name = value.getName();
String sex = value.getSex();
int age = value.getAge();
System.out.println("我是" + name + ",今年" + age + "岁,是一名" + sex + "生。");
}System.out.println("===========使用Iterator============");
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
System.out.println("key:" + key);
Student value = https://www.it610.com/article/map.get(key);
String name = value.getName();
String sex = value.getSex();
int age = value.getAge();
System.out.println("我是" + name + ",今年" + age + "岁,是一名" + sex + "生。");
}System.out.println("===========使用Entry============");
for (Entry entry : map.entrySet()) {
String key = entry.getKey();
Student value = https://www.it610.com/article/entry.getValue();
System.out.println("key:" + key);
String name = value.getName();
String sex = value.getSex();
int age = value.getAge();
System.out.println("我是" + name + ",今年" + age + "岁,是一名" + sex + "生。");
}System.out.println("===========map转list,然后list里的元素为entry============");
List list = new ArrayList(map.entrySet());
for (Entry entry : list) {
String key = entry.getKey();
Student value = https://www.it610.com/article/entry.getValue();
System.out.println("key:" + key);
String name = value.getName();
String sex = value.getSex();
int age = value.getAge();
System.out.println("我是" + name + ",今年" + age + "岁,是一名" + sex + "生。");
}
}
}