[简单]拼接字符串

         工作中遇到需要从Map里面取值拼接字符串的情况,自己写了个,不是很好,欢迎提出更优雅的写法,代码如下

         

import java.util.HashMap;
import java.util.Map;

public class 拼接字符串 {
    
	public String getResult(Map<String, String> parasMap){
		if(parasMap==null||parasMap.size()==0){
			return "";
		}
		String result=new String();
		for(Map.Entry<String,String> entry:parasMap.entrySet()){
			if("T_A".equals(entry.getKey())&&"1".equals(entry.getValue())){
				if(result.length()>0){
					result+="、黑格尔";
				}else{
					result+="黑格尔";
				}
			}else if("A_B".equals(entry.getKey())&&"1".equals(entry.getValue())){
				if(result.length()>0){
					result+="、叔本华";
				}else{
					result+="叔本华";
				}
			}else if("V_P".equals(entry.getKey())&&"1".equals(entry.getValue())){
				if(result.length()>0){
					result+="、康德";
				}else{
					result+="康德";
				}
			}
		}
		if(result.length()>0){
			return result+" 等";
		}
		return " ";
	}
	public static void main(String[] args) {
		拼接字符串 t=new 拼接字符串();
		Map<String,String> paramMap=new HashMap<String, String>();
		paramMap.put("V_P","1");
		paramMap.put("T_A","0");
		paramMap.put("A_B","1");
		System.out.println(t.getResult(paramMap));
	}

}

 

      结果为

   

叔本华、康德 等

  

  -------------------------------------------------------2014-8-24添加------------------------------------------------------

   修改后的代码:

public String getResult(Map<String, String> parasMap){
		if(parasMap==null||parasMap.size()==0){
			return "";
		}
		StringBuffer result=new StringBuffer();
		for(Map.Entry<String,String> entry:parasMap.entrySet()){
			if("T_A".equals(entry.getKey())&&"1".equals(entry.getValue())){
				result.append("、黑格尔");
			}else if("A_B".equals(entry.getKey())&&"1".equals(entry.getValue())){
				result.append("、叔本华");
			}else if("V_P".equals(entry.getKey())&&"1".equals(entry.getValue())){
				result.append("、康德");
			}
		}
		if(result.length()>0){
			 result.append(" 等");
			 return result.substring(1);
		}
		return " ";
	}

 

   全文完

 

你可能感兴趣的:(字符串)