gpt4 book ai didi

java - 按字母顺序对数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:29:04 26 4
gpt4 key购买 nike

我有一个数组,我需要按出现次数然后按字母顺序对它的元素进行排序。例如:

55 The
32 ASomething
32 BSomething

ASomething should come before Bsomething because:
1) they have the same number
2) A comes before B alphabetically

所以你先按出现次数排序,然后按字母顺序排序

最好的方法是什么。我正在使用合并排序对计数进行排序,但我如何声明它将检查它们是否具有相同的数字,它按字母顺序排序(可能超过 2 个单词)。

解决方案:我所做的是在对数据计数进行合并排序之前对数据进行合并排序,这已经足够好了:)感谢大家的帮助

最佳答案

您需要一个自定义 Comparator为此使用 Arrays.sort() :

Arrays.sort(array, new CustomComparator());

public class CustomComparator implements Comparator<String> {
private final Pattern pattern = Pattern.compile("(\\d+)\\s+(.*)");

public int compare(String s1, String s2) {
Matcher m1 = pattern.matcher(s1);
if (!m1.matches()) {
throw new IllegalArgumentException("s1 doesn't match: " + s1);
}
Matcher m2 = pattern.matcher(s2);
if (!m2.matches()) {
throw new IllegalArgumentException("s2 doesn't match: " + s2);
}
int i1 = Integer.parseInt(m1.group(1));
int i2 = Integer.parseInt(m2.group(1));
if (i1 < i2) {
return 1;
} else if (i1 > i2) {
return -1;
}
return m1.group(2).compareTo(m2.group(2));
}
}

对于 Collections你可以使用 Collections.sort()

以上假定您的数组元素是 String,例如 "22 ASomething",而不是包含事件和一些文本的特定数据结构。如果是这种情况,您可以使用更简单的 Comparator

此外,如果您确实有一个 String 数组,可能值得首先将其转换为一个已解析的对象数组,以保存对元素的过度解析(即某些元素将被解析不止一次)。

关于java - 按字母顺序对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2376134/

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