java.util.Map输出方式

时间:2022-07-18 19:37:10
packagecn.tty.map;
public classStudent {
    public static final int MALE=0;
    public static final int FEMALE=1;
    privateString stuNum;
    privateString stuName;
    private int gender;
    publicStudent(){
    }
    publicStudent(String stuNum,String stuName,intgender){
       this.stuNum=stuNum;
       this.stuName=stuName;
       this.gender=gender;
    }
   
    publicString getStuNum() {
       return stuNum;
    }
    public voidsetStuNum(String stuNum) {
       this.stuNum = stuNum;
    }
    publicString getStuName() {
       return stuName;
    }
    public voidsetStuName(String stuName) {
       this.stuName = stuName;
    }
    public intgetGender() {
       return gender;
    }
    public voidsetGender(int gender) {
       this.gender = gender;
    }
    publicString toString(){
       return stuNum+"|"+stuName+"|"+gender;
    }
}
 
packagecn.tty.map;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.Map;
importjava.util.Set;
public classMapInput {
    public static voidmain(String[] args) {
       //取得java.util.Map中的中的键和值
       Map<String,Student> map=newHashMap<String,Student>();
       map.put("No.001", newStudent("001","tty",Student.MALE));
       map.put("No.002", newStudent("002","hyl",Student.FEMALE));
      
       System.out.println("输出方式一:");
       Set<Map.Entry<String,Student>> set=map.entrySet();
       Iterator<Map.Entry<String,Student>> iter=set.iterator();
       while(iter.hasNext()){
           Map.Entry<String, Student> entry=iter.next();
           System.out.println("key-->"+entry.getKey());
           System.out.println("value-->"+entry.getValue());
       }
       System.out.println("输出方式二:");
       for(Map.Entry<String, Student> entry:map.entrySet()){
           System.out.println("key-->"+entry.getKey());
           System.out.println("value-->"+entry.getValue());
       }
      
       System.out.println("输出方式三:");
       Set<String> keySet=map.keySet();
       Iterator<String> iterator=keySet.iterator();
       while(iterator.hasNext()){
           String key=iterator.next();
           Student val=map.get(key);
           System.out.println("key-->"+key);
           System.out.println("value-->"+val);
       }
    }
}