【JavaDemo】使用Entry遍歷含自定義類的Map集合
阿新 • • 發佈:2019-01-29
含有自定義類的Map遍歷 Demo2
- 此Demo演示方法2:獲取鍵值對物件Entry,然後用Entry分別鍵獲取鍵和值。
- 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 + "]";
}
}
遍歷類MapDemo2
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/*
* 使用Map遍歷自定義型別
* 遍歷方式:方法2,取出Map中所有的鍵值對物件Entry,根據Entry物件獲取key和value。
*/
public class MapDemo2 {
public static void main(String[] args) {
//定義Singer物件
Singer s1 = new Singer("田馥甄","小幸運");
Singer s2 = new Singer("孫燕姿","天黑黑");
Singer s3 = new Singer("周杰倫","晴天");
Singer s4 = new Singer("不 才","你有沒有見過他");
//定義一個Map
Map<String,Singer> map = new HashMap<>();
//將Singer物件新增到Map中
map.put("001", s1);
map.put("002", s2);
map.put("003", s3);
map.put("004", s4);
//獲取Entry物件
Set<Entry<String, Singer>> entrySet = map.entrySet();
//列印標題
System.out.println("\t\t"+"編號"+"\t\t"+"姓名"+"\t\t\t\t"+"歌曲");
//遍歷每個Entry物件,通過Entry物件獲取對應的歌手姓名和歌曲名稱
for (Entry<String, Singer> entry : entrySet) {
System.out.println("\t\t"+entry.getKey()+"\t\t"+entry.getValue().getName()+"\t\t"+entry.getValue().getSongName());
}
}
}