使用场景
比如我们在调用某个Http业务接口,或者调用一个入参为Map
类型参数方法根据条件查询数据,对于此种情况,Map
中的key
值得个数是根据业务需求而不同的,而且当需要向业务接口或者方法参数多个条件的时候,这时我们使用原生的map.put()
就显得代码不优雅,可能我们的代码会是类似下面这样:
Map<String, String> mapParam = new HashMap<>();
mapParam.put("key1", "value1");
mapParam.put("key2", "value2");
mapParam.put("key3", "value3");
mapParam.put("key4", "value4");
mapParam.put("key5", "value5");
mapParam.put("key6", "value6");
下面编写一个简单的工具类来使得构建map参数的过程变得优雅好看些,代码如下
package com.zhegui.utils.builders;
import java.util.HashMap;
import java.util.Map;
/**
* 一个简单的mapParam构建器
* @author Zhegui
*
* @param <K>
* @param <V>
*/
public class MapParamBuilder<K, V>{
private Map<K,V> mapParam;
/**
* 默认构造函数
*/
public MapParamBuilder(){
mapParam = ne