java与freemarker中map的遍历

来源:互联网 发布:syntaxhighlighter.js 编辑:程序博客网 时间:2024/05/20 20:22

java中部分时间都是要的是list集合,偶尔会使用到map集合,但是经常会忘记map集合的如何遍历,今天记录下:

java中的遍历

复制代码
import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import java.util.Map.Entry;/** * map遍历的三种办法 * @author us * */public class test2{   public static void main(String[] args)    {           /**        * new一个map,然后添加内容        */       Map map=new HashMap();       for (int i = 0; i < 10; i++)        {            map.put(i+"",i+"");            System.out.println("添加"+i+"成功");        }       System.out.println("map大小"+map.size());              /**        * 1.把值放到一个集合力,然后便利集合        */       Collection c=map.values();       Iterator it= c.iterator();       for (; it.hasNext();)        {            System.out.println(it.next());        }              /**        * 2.把key放到一个集合里,遍历key值同时根据key得到值 (推荐)        */       Set set =map.keySet();       Iterator it=set.iterator();       while(it.hasNext()){           String s= (String) it.next();           System.out.println(map.get(s));       }              /**        * 3.把一个map对象放到放到entry里,然后根据entry同时得到key和值        */       Set set =map.entrySet();       Iterator it=set.iterator();       while(it.hasNext()){           Map.Entry<String, String>  entry=(Entry<String, String>) it.next();           System.out.println(entry.getKey()+":"+entry.getValue());                  }           }}
复制代码

freemarker中map集合的遍历:

复制代码
    <table width="300" border =1>        <thead>            <tr>                <th width="100">来源方式</th>                <th width="120">人数</th>            </tr>        </thead>        <tbody>            <#if clientSourceData?exists>                <#list clientSourceData?keys as key>                    <tr>                           <td>${key}</td>                           <td>${clientSourceData.get(key)}</td>                   </tr>                </#list>            </#if>            <tr>                   <td>合计:</td>                   <td>${totalNum}</td>           </tr>        </tbody>    </table>
复制代码