有的时候,我们需要对一份数据,产生不同的工单,需要进行字段的映射,常规的方法,使用Map或者JsonObject存储,key都存储为小写。
但是其实没必要,处理方案有如下三种:
1.自己手写比较器
Map<String, Object> map = new TreeMap<String, Object>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// 在这里忽略大小写比较
if (o1.compareToIgnoreCase(o2) == 0) {
return 0;
}
return 1;
}
});
2.借助TreeMap重载的一个构造方法
Map<String, String> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
稍微来看下TreeMap的构造方法:(JDK1.8支持传Comparator,SortMap和Map多种参数)
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
再来看下String.CASE_INSENSITIVE_ORDER
它实际上是
public static final Comparator<String> CASE_INSENSITIVE_ORDER
= new CaseInsensitiveComparator();
private static class CaseInsensitiveComparator
implements Comparator<String>, java.io.Serializable {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 8575799808933029326L;
public int compare(String s1, String s2) {
int n1 = s1.length();
int n2 = s2.length();
// 以最短的字符串作为基准,逐个字符转小写,转大写比较
int min = Math.min(n1, n2);
for (int i = 0; i < min; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
if (c1 != c2) {
// No overflow because of numeric promotion
return c1 - c2;
}
}
}
}
return n1 - n2;
}
3,最后就是使用 CaseInsensitiveMap
需要引入依赖,默认实现就是忽略大小写的。
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
done.