Map是以键值对的形式来存储数据的Map
public class Demo02 {
public static void main(String[] args) {
Map<String, Double> m = new HashMap<>();
m.put("张三", 59.0);
m.put("张三1", 59.0);
m.put("张三3", 59.0);
m.put("张三2", 85.0);
System.out.println(m);
/*
* 通过key组成的Set集合遍历map
*/
//1、获取mao中所有key组成的Set
Set<String> s = m.keySet();
//2、对这个keySet进行遍历
Iterator<String> it = s.iterator();
while (it.hasNext()) {
String str = it.next();
System.out.println(m.get(str));
}
}
}
如果存放的是对象:
Student.java
public class Student {
private String name;
private int age;
private String sex;
private double score;
public Student(String name, int age, String sex, double score) {
super();
this.name = name;
this.age = age;
this.sex = sex;
this.score = score;
}
public Student() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", sex=" + sex
+ ", score=" + score + "]";
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
Teacher.java:
public class Teacher {
private String name;
public Teacher(String name) {
super();
this.name = name;
}
public Teacher() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Teacher [name=" + name + "]";
}
}
Main.java
package com.zhongbei.www.map02;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class TheMainClass {
public static void main(String[] args) {
Map<Student, Teacher> map = new HashMap<Student, Teacher>();
map.put(new Student("小狄", 15, "女",3), new Teacher("Great Song"));
map.put(new Student("王鹏", 5, "女",15), new Teacher("Bo Li"));
map.put(new Student("小人", 15, "不详", 65), new Teacher("老王"));
map.put(new Student("小杰", 16, "男", 95), new Teacher("sam"));
Set<Entry<Student, Teacher>> entrySet = map.entrySet() ;
for (Entry<Student, Teacher> e : entrySet) {
//e就是键值对组成的对象。
//可以通过e取出键值对的键和值
Student s = e.getKey();
Teacher t = e.getValue();
System.out.println(s);
System.out.println(t);
}
}
}