遍历Map的几种方式

/**
 * 
 */
package com.hn.map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


public class SetDemo {
	public static void main(String[] args) {
		 HashMap hm=new HashMap();
		 hm.put(new Student("shuiyin4",23), "beji");
		 hm.put(new Student("shuiyin3",13), "zs");
		 hm.put(new Student("shuiyin2",43), "sz");
		 hm.put(new Student("shuiyin1",33), "gz");
		 entrySet(hm);
		 iterator(hm);
		 map(hm);
		 keySetIterator(hm);
	}
	public static void entrySet(HashMap hm){
		for(Map.Entry entry:hm.entrySet()){
			System.out.println("key:"+entry.getKey()+",value:"+entry.getValue());
		}
		;
	}
	public static void iterator(HashMap hm){
		Iterator> ite= hm.entrySet().iterator();
		while(ite.hasNext()){
			Map.Entry map= ite.next();
			System.out.println(map.getKey()+"---"+map.getValue());
		}
	}
	public static void map(HashMap hm){
		for(Student stu: hm.keySet()){
			String value= hm.get(stu);
			System.out.println(stu.toString()+"---"+value);
		}
	}
	public static void keySetIterator(HashMap hm){
		Set stuS=hm.keySet();
		Iterator stui= stuS.iterator();
		while(stui.hasNext()){
			Student stu= stui.next();
			System.out.println(stu.toString()+""+hm.get(stu));
			
		}
	}
}
/**
 * 
 */
package com.hn.map;


public class Student implements Comparable {
	private String name;
	private int age;

	Student(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	// 复写equals
	public boolean equals(Object obj) {
		if (!(obj instanceof Student)) {
			return false;
		}
		Student p = (Student) obj;
		return this.name.equals(p.name) && this.age == p.age;
	}

	// 复写hashCode
	public int hashCode() {
		return name.hashCode() + age * 31;
	}

	public int compareTo(Student s) {// 已经明确指明是学生类所以不用obj
		int num = this.age - s.age;
		if (num == 0)
			return this.name.compareTo(s.name);
		return num;
	}

	public String toString() {
		return name + "--->" + age;
	}
}


你可能感兴趣的:(javase,集合类)