This article shares with you the example of Java implementation simple template rendering for your reference. The specific content is as follows
Code
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} was born in ${graduateYear}, and graduated from ${university} in ${map}."; Map<String,String> params = new HashMap<>(); params.put("name","Zhang San"); params.put("sex","male"); params.put("birthYear","1990"); params.put("graduateYear","2012"); params.put("university","Tsinghua 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){ //Use builder splicing to improve a lot of efficiency than string addition StringBuilder builder = new StringBuilder(); //Define the control variable boolean $Begin = false; boolean paramBegin = false; //boolean paramEnd = false; StringBuilder key = null; //Loop match for(int i=0;i<template.length();i++){ char c = template.charAt(i); //Start identification if(c=='$'){ $Begin = true; } if($Begin && c=='{'){ paramBegin = true; builder.deleteCharAt(builder.length()-1); //Delete the added $character key = new StringBuilder(); continue; } //Parameter key if(paramBegin && c!='}'){ if(c=='{'){ System.out.println("Template format error! Position: "+i); }else { key.append(c); } continue; } //End tag if(paramBegin && c=='}'){ //paramEnd = true; //The value corresponding to the parameter key builder.append(params.get(key.toString())); //Reset the control variable $Begin = false; paramBegin = false; //paramEnd = false; continue; } //Default builder.append(c); //Add characters} 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; }}Running results
Zhang San, male, born in 1990, graduated from Tsinghua University in 2012.
cost time:65ms
Zhang San, male, born in 1990, graduated from Tsinghua University in 2012.
cost time:161ms
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.