含有自定义类的Map遍历 Demo1
- 此Demo演示方法1:先获取所有的键key的Set集合,然后根据键获取值。
- Map含有自定义类Singer。
自定义类Singer
//歌手类
public class Singer {
private String name;
private String songName;
public Singer(String name, String songName) {
super();
this.name = name;
this.songName = songName;
}
public Singer() {
super();
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSongName() {
return songName;
}
public void setSongName(String songName) {
this.songName = songName;
}
@Override
public String toString() {
return "Singer [name=" + name + ", songName=" + songName + "]";
}
}
遍历类MapDemo
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/*
* 使用Map遍历自定义类型
* 遍历方式:方法1,取出Map中所有的key,根据key获取值。
*/
public class MapDemo {
public static void main(String[] args) {
//创建歌手
Singer s1 = new Singer("邓紫棋", "泡沫");
Singer s2 = new Singer("银 临", "牵丝戏");
Singer s3 = new Singer("谢春花", "只道寻常");
Singer s4 = new Singer("Taylor", "TikTok");
Map<String,Singer> map = new HashMap<>();
map.put("001",s1);
map.put("002",s2);
map.put("003",s3);
map.put("004",s4);
//获取key集合
Set<String> keySet = map.keySet();
//打印输出
System.out.println("\t"+"编号"+"\t\t"+"姓名"+"\t\t\t"+"歌曲");
//遍历key,并通过key获取Singer对象。然后通过这个对象获取歌手姓名和歌曲名
for (String key : keySet) {
System.out.println("\t"+key+"\t\t"+map.get(key).getName()+"\t\t"+map.get(key).getSongName());
}
}
}