Map 数据类型详解 基本概念 Map 是一种 键值对(Key-Value) 的数据结构,用于存储一对一的映射关系。
K (Key) : 键,用于唯一标识一个值,类似字典的目录索引
V (Value) : 值,与键关联的实际数据
类比理解 :就像一本字典,K是要查的词,V是词的解释。
基本特性 1 2 3 4 5 6 7 8 9 10 11 12 Map<String, Integer> ageMap = new HashMap <>(); ageMap.put("张三" , 25 ); ageMap.put("李四" , 30 ); Integer age = ageMap.get("张三" ); ageMap.put("张三" , 26 );
常见实现类
HashMap : 最常用,无序,允许null键和值
LinkedHashMap : 保持插入顺序
TreeMap : 按键自动排序
ConcurrentHashMap : 线程安全
在 Spring 框架中的常见应用 1. 接收前端传递的动态参数 1 2 3 4 5 6 7 8 9 10 11 12 @RestController public class UserController { @PostMapping("/user/update") public String updateUser (@RequestBody Map<String, Object> params) { String name = (String) params.get("name" ); Integer age = (Integer) params.get("age" ); return "success" ; } }
2. 返回灵活的响应数据 1 2 3 4 5 6 7 8 @GetMapping("/user/info") public Map<String, Object> getUserInfo () { Map<String, Object> result = new HashMap <>(); result.put("code" , 200 ); result.put("message" , "成功" ); result.put("data" , userObject); return result; }
3. 依赖注入中管理Bean集合 1 2 3 4 5 6 7 8 9 10 11 12 @Configuration public class PaymentConfig { @Autowired private Map<String, PaymentService> paymentServices; public PaymentService getPaymentService (String type) { return paymentServices.get(type); } }
4. 缓存管理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Service public class CacheService { private Map<String, Object> cache = new ConcurrentHashMap <>(); public void put (String key, Object value) { cache.put(key, value); } public Object get (String key) { return cache.get(key); } }
5. 动态SQL参数(MyBatis) 1 2 3 4 5 6 @Mapper public interface UserMapper { List<User> selectByConditions (Map<String, Object> conditions) ; }
1 2 3 4 5 6 7 8 9 10 <select id ="selectByConditions" resultType ="User" > SELECT * FROM user WHERE 1=1 <if test ="name != null" > AND name = #{name} </if > <if test ="age != null" > AND age = #{age} </if > </select >
6. 配置属性映射 1 2 3 4 5 6 7 8 9 10 11 @Component @ConfigurationProperties(prefix = "app") public class AppConfig { private Map<String, String> settings; }
实际应用示例 策略模式实现 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Service public class OrderService { @Autowired private Map<String, PaymentStrategy> paymentStrategyMap; public void pay (String paymentType, BigDecimal amount) { PaymentStrategy strategy = paymentStrategyMap.get(paymentType); strategy.pay(amount); } } @Component("alipay") public class AlipayStrategy implements PaymentStrategy { }@Component("wechat") public class WechatStrategy implements PaymentStrategy { }
总结
K : 唯一标识符,用于快速查找
V : 与K关联的实际数据
Spring中 : 主要用于灵活处理动态数据、管理Bean集合、实现策略模式等场景
Map的核心优势是通过键快速定位值 ,时间复杂度O(1),非常高效!