gpt4 book ai didi

java - 如何通过考虑点(.) 进行排序

转载 作者:行者123 更新时间:2023-12-01 16:47:19 26 4
gpt4 key购买 nike

我的rowId如下所示,它将遵循父子关系

1
1.1
1.1.1
2
2.1
.
.
.
9
9.1
.
9.9
10
10.1

我正在使用以下代码使用 rowid 对 Bean 进行排序

List<MyBean> sortedList = rootItems.stream().sorted(Comparator.comparing(MyBean::getRowId)) .collect(Collectors.toList());

如果我像上面那样排序,那么它会像下面这样排序

10
11
12
.
.
19
2
2.1
.
.
3
.
.

不应该是这样的。

我想像上面给出的 rowid 示例一样进行排序。

有人建议我遵循他的代码..即...

private static final Pattern SINGLE_DIGIT = Pattern.compile("\\b(\\d)\\b");
static String padWithZeroes(String InputString, int digits) {
final Matcher matcher = SINGLE_DIGIT.matcher(InputString);
StringBuffer sb = new StringBuffer();
while(matcher.find()){

matcher.appendReplacement(sb, pad(digits - matcher.group().length())+matcher.group());
}
matcher.appendTail(sb);
return sb.toString();
}

static String pad(int length) {
final char[] chars = new char[length];
Arrays.fill(chars, '0');
return new String(chars);
}

如果我遵循他的代码,它会返回一个字符串,但不是对象列表。我该如何使用该代码。请帮助我。

最佳答案

您可以比较两个字符串,而无需实际拆分它们:

int compare(String a, String b) {
int ai = 0, bi = 0;
while (ai < a.length() && bi < b.length()) {
// Extract the next int from a.
int an = 0;
while (ai < a.length() && a.charAt(ai) != '.') {
an = 10*an + Character.getNumericValue(a.charAt(ai));
++ai;
}
++ai; // Skip the dot.

// Extract the next int from b.
int bn = 0;
while (bi < b.length() && b.charAt(bi) != '.') {
bn = 10*bn + Character.getNumericValue(b.charAt(bi));
++bi;
}
++bi; // Skip the dot.

// Compare these ints, and return if they're different.
int cmp = Integer.compare(an, bn);
if (cmp != 0) return cmp;
}
// If we reached the end of one string but not the other,
// the one we didn't reach the end of is "after" the first.
if (ai < a.length()) return 1;
if (bi < b.length()) return -1;
return 0;
}

Ideone demo

您可以使用它通过构造 Comparator<MyBean> 对列表元素进行排序:

List<MyBean> sortedList =
rootItems.stream()
.sorted((b1, b2) -> compare(b1.getRowId(), b2.getRowId())
.collect(Collectors.toList());

关于java - 如何通过考虑点(.) 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47941618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com