[英]Order a TreeMap with custom comparator like Excel coordinate order
I'm using a TreeMap
and its subMap
to manage Excel files. 我使用的是
TreeMap
和它subMap
来管理Excel文件。 I use as key the Excel coordinate. 我将Excel坐标用作键。
In Excel the order is like A
, B
, C
, ..., AA
, AB
, AC
, ..., BA
... but the order I have is A
, AA
, AAA
, AB
, ..., B
. 在Excel中,顺序类似于
A
, B
, C
,..., AA
, AB
, AC
,..., BA
...,但是我的顺序为A
, AA
, AAA
, AB
,..., B
。
I thought the solution is to use a custom comparator but I don't know how to make it to obtain Excel alphabetical order. 我以为解决方案是使用自定义比较器,但我不知道如何使其获得Excel字母顺序。
Comparator<String> excelOrder= new Comparator<String>() {
@Override public int compare(String s1, String s2) {
//make order
}
};
and then use 然后使用
SortedMap<String,String> map = new TreeMap<String,String>(secondCharComparator);
First, you want to compare the String by their length (using String.length()
) and then lexicographically (this is exactly what's done by default with String.compareTo(other)
). 首先,您想按字符串的长度比较String(使用
String.length()
),然后按字典顺序进行比较(这正是默认情况下使用String.compareTo(other)
)。 The following does exactly that: 以下正是这样做的:
Comparator<String> excelOrder = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
int s1Length = s1.length();
int s2Length = s2.length();
if (s1Length < s2Length) {
return -1;
} else if (s1Length > s2Length) {
return 1;
} else {
return s1.compareTo(s2);
}
}
};
Note that if you are using Java 8, this can be written a lot more simply (this code is using the following static import import static java.util.Comparator.comparingInt;
): 请注意,如果您使用的是Java 8,则可以编写得更简单(此代码使用以下静态导入
import static java.util.Comparator.comparingInt;
):
Comparator<String> excelOrder = comparingInt(String::length).thenComparing(String::compareTo);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.