java 不区分KEY大小写的MAP

本文介绍了如何使用Apache Commons Collections中的CaseInsensitiveMap实现不区分大小写的键值匹配。通过对比HashMap,展示了CaseInsensitiveMap的具体用法及注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时候我们会需要一个不区分KEY大小写的MAP,今天介绍一个apache.commons包里的类:
org.apache.commons.collections.map.CaseInsensitiveMap


例子:

 public static void main(String[] args) {
  Map<String, Object> result = new CaseInsensitiveMap(); 
  result.put("aaa", "ok");
  System.out.println(result.get("aaa"));
  System.out.println(result.get("aAa"));
  System.out.println(result.get("AAa"));
  System.out.println(result.get("AAA"));
}

输出:

ok
ok
ok
ok

 

而HashMap是要区分大小写的

例子:

public static void main(String[] args) {
 Map<String, String> result = new HashMap<String, String>(); 
 result.put("aaa", "ok");
 System.out.println(result.get("aaa"));
 System.out.println(result.get("aAa"));
 System.out.println(result.get("AAa"));
 System.out.println(result.get("AAA"));
}

输出:

ok
null
null
null

 

若需要把HashMap转为CaseInsensitiveMap,需要putAll,直接等于是不生效的。

正确:

Map map = new HashMap();
Map map1 = new CaseInsensitiveMap();
map1.putAll(map );

错误:

Map map = new HashMap();
Map map1 = new CaseInsensitiveMap();
map1 = map;//不生效,依旧区分大小写

 

转载于:https://my.oschina.net/u/2351298/blog/1834010

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值