java與freemarker中map的遍歷


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>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM