HashMap 和TreeMap的遍历

遍历核心用到Map的Entry以及迭代器:Iterator

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); } } }

 

附:http://www.oracle.com/technology/global/cn/pub/articles/maps1.html这篇文章讲Map非常详细。

    原文作者:xiaoranchenxi
    原文地址: https://blog.csdn.net/xiaoranchenxi/article/details/4008351
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞