使用Map<key,value>数据结构时,如果要忽略key的大小写敏感,可以使用TreeMap,构造函数传入String.CASE_INSENSITIVE_ORDER比较器,它是一个忽略大小写的Comparator对象。
使用示例如下:
Map<String, String> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
在mysql-connector-java的ResultSetImpl类中,就使用了大小写不敏感的TreeMap对象来存储字段名和值,因为MySQL中字段名是不区分大小写的。
public void buildIndexMapping() throws SQLException { int numFields = this.fields.length; this.columnLabelToIndex = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER); this.fullColumnNameToIndex = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER); this.columnNameToIndex = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER); ...
完整示例:
package com.taoxi.mybatis.mysimple; import org.junit.Test; import java.util.TreeMap; public class MysimpleApplicationTests { @Test public void testMapCaseInsensitive() { TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER); treeMap.put("KEY1", 11); treeMap.put("key2", 22); Integer key2 = treeMap.get("Key2"); System.out.println("key2's value is " + key2.toString()); } }
结果:
key2's value is 22