本文實例為大家分享了Java實現簡單的模板渲染,供大家參考,具體內容如下
代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
|
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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/hdwang/p/8064440.html