HashMap和TreeMap的遍历

概述:

(1)HashMap遍历是没有顺序的,TreeMap的遍历是有顺序的;

(2)针对Map的遍历都要转化成Map.Entry对象,通过方法Map.entrySet()得到该对象Set

(3)通过迭代器Iterator将Map遍历;

(4)

详细参考如下:

import java.util.*;
import java.util.Map.Entry;

public class Test {
	public static void main(String[] args) {
		//HashMap 遍历是不按顺序排列
		Map map=new HashMap();
		map.put("m1", "m11");
		map.put("m2", "m22");
		map.put("m3", "m33");
		map.put("m4", "m44");
		Iterator iter=map.entrySet().iterator();
		while(iter.hasNext()){
			Map.Entry entry=(Entry) iter.next();
			String key=entry.getKey().toString();
			String value=entry.getValue().toString();
			System.out.println(key+"*"+value);
		}
		
		//TreeMap 遍历是按顺序排列
		Map treemap=new TreeMap();
		treemap.put("t1", "t11");
		treemap.put("t2", "t22");
		treemap.put("t3", "t33");
		treemap.put("t4", "t44");
		treemap.put("t5", "t55");
		
		Iterator titer=treemap.entrySet().iterator();
		while(titer.hasNext()){
			Map.Entry ent=(Map.Entry )titer.next();
			String keyt=ent.getKey().toString();
			String valuet=ent.getValue().toString();
			System.out.println(keyt+"*"+valuet);
		}
		
	}
	

}

猜你喜欢

转载自blog.csdn.net/zdb292034/article/details/83351507