【JavaDemo】使用Entry遍历含自定义类的Map集合

含有自定义类的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());
        }

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值