方式一:通过keySet获取键,然后通过get获取值
方式二:获取每一个map对象,然后在获取其中的键和值
package day41;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapDemo01 {
public static void main(String[] args) {
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"A");
map.put(2,"B");
//方式一遍历map
//获取所有的key键
Set<Integer> keySet = map.keySet();
//增强for获取每个key值
for(Integer key:keySet){
System.out.println(key+","+map.get(key));
}
//方式二
//获取所有的对象
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
//通过增强for来获取键和值
for(Map.Entry<Integer, String> me:entrySet){
System.out.println(me.getKey()+","+me.getValue());
}
}
}
示例:学生类,键唯一值的代码实现。需要重写hashCode() 和equals()两个方法。注意这两个方法是自动生成的。、
package day41;
import java.util.Objects;
//学生类
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name, int age){
this.name = name;
this.age = age;
}
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;
}
//通过Java inteliJ 的code里面找到generate,里面找到equals和hashCode即可自动重写
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
package day41;
import java.util.HashMap;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<Student,String> hm = new HashMap<Student,String>();
Student s1 = new Student("A",5);
Student s2 = new Student("B",1);
Student s3 = new Student("C",3);
Student s4 = new Student("C",3);
hm.put(s1,"美国");
hm.put(s2,"日本");
hm.put(s3,"加拿大");
//想要相同的key,后面put的会覆盖之前的。需要Student类中重写两个方法
hm.put(s4,"挪威");
Set<Student> keySet = hm.keySet();
for(Student key:keySet){
System.out.println(key.getName()+key.getAge()+hm.get(key));
}
}
}