问题描述
我有这个功能,可以按数字顺序对数据行进行排序,但是问题是它的键是由字母和数字组成的:
I have this function that sorts my lines of data by numerical order, but the problem is that the key it sorts by composed from letters and numbers:
void writeData(Map<String, Params> data) {
.
.
StringBuilder sb = new StringBuilder();
data.values()
.stream()
.sorted(Comparator.comparing(Params::getIdx))
.forEach(r -> {
sb.append(System.lineSeparator());
sb.append(r.getCSVRow());
});
.
.
}
例如,我有以下字符串:"A100","A101","A99"
.
For example I have the strings:"A100","A101", "A99"
.
我得到的订单:
A100
A101
A99
我要的订单:
A99
A100
A101
如何更改此功能?由于某种原因,我无法选择使用 thenCompare
.(不过,我已经读过它.)
How can I change this function?I don't have an option to use thenCompare
for some reason. (I've read about it though).
推荐答案
从字法上讲这是正确的排序,因为字符 9
字符 1
.您应该将这些字符串分成非数字部分和数字部分,并分别进行排序:数字作为数字,字符串作为字符串.排序后,您可以将这些部分重新组合为一个字符串,并获得排序后的数组.例如:
Lexicographically this is the correct sorting, because character 9
goes after character 1
. You should split these strings into non-numeric and numeric parts and sort them separately: numbers as numbers, and strings as strings. After sorting you can join these parts back into one string and get a sorted array. For example:
// assume a string consists of a sequence of
// non-numeric characters followed by numeric characters
String[] arr1 = {"A100", "A101", "A99", "BBB33", "C10", "T1000"};
String[] arr2 = Arrays.stream(arr1)
// split string into an array of two
// substrings: non-numeric and numeric
// Stream<String[]>
.map(str -> str
// add some delimiters to a non-empty
// sequences of non-numeric characters
.replaceAll("\\D+", "$0\u2980")
// split string into an array
// by these delimiters
.split("\u2980"))
// parse integers from numeric substrings,
// map as pairs String-Integer
// Stream<Map.Entry<String,Integer>>
.map(row -> Map.entry(row[0], Integer.parseInt(row[1])))
// sort by numbers as numbers
.sorted(Map.Entry.comparingByValue())
// intermediate output
//C=10
//BBB=33
//A=99
//A=100
//A=101
//T=1000
.peek(System.out::println)
// join back into one string
.map(entry -> entry.getKey() + entry.getValue())
// get sorted array
.toArray(String[]::new);
// final output
System.out.println(Arrays.toString(arr2));
// [C10, BBB33, A99, A100, A101, T1000]
这篇关于如何使用sorted(comparator)方法按字典顺序排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!