本文實例為大家分享了Java實現簡單的模板渲染,供大家參考,具體內容如下
代碼
package com.hdwang;import java.util.HashMap;import java.util.Map;/** * Created by hdwang on 2017/12/19. */public class MyTemplate { public static void main(String[] args){ String template = "${name},${sex},${birthYear}年出生,${graduateYear}年畢業于${university}。"; Map<String,String> params = new HashMap<>(); params.put("name","張三"); params.put("sex","男"); params.put("birthYear","1990"); params.put("graduateYear","2012"); params.put("university","清華大學"); long start = System.currentTimeMillis(); for(int i=0;i<10000;i++) { String result = render(template, params); if(i==9999) { System.out.println(result); } } long end = System.currentTimeMillis(); System.out.println("cost time:"+(end-start)+"ms"); start = System.currentTimeMillis(); for(int i=0;i<10000;i++) { String result = render2(template, params); if(i==9999) { System.out.println(result); } } end = System.currentTimeMillis(); System.out.println("cost time:"+(end-start)+"ms"); } public static String render(String template,Map<String,String> params){ //使用builder拼接,比string相加提高不少效率 StringBuilder builder = new StringBuilder(); //定義控制變量 boolean $Begin = false; boolean paramBegin = false; //boolean paramEnd = false; StringBuilder key = null; //循環匹配 for(int i=0;i<template.length();i++){ char c = template.charAt(i); //開始標識 if(c=='$'){ $Begin = true; } if($Begin && c=='{'){ paramBegin = true; builder.deleteCharAt(builder.length()-1); //刪除添加的$字符 key = new StringBuilder(); continue; } //參數key if(paramBegin && c!='}'){ if(c=='{'){ System.out.println("模板格式錯誤!位置:"+i); }else { key.append(c); } continue; } //結束標識 if(paramBegin && c=='}'){ //paramEnd = true; //拼接參數key對應的值 builder.append(params.get(key.toString())); //重置控制變量 $Begin = false; paramBegin = false; //paramEnd = false; continue; } //默認情況 builder.append(c); //添加字符 } return builder.toString(); } public static String render2(String template,Map<String,String> params){ for(Map.Entry<String,String> entry:params.entrySet()){ String key = entry.getKey(); String value = entry.getValue(); template = template.replace("${"+key+"}",value); } return template; }}
運行結果
張三,男,1990年出生,2012年畢業于清華大學。
cost time:65ms
張三,男,1990年出生,2012年畢業于清華大學。
cost time:161ms
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選