gpt4 book ai didi

java - 从排序对象数组到 ArrayList
转载 作者:太空狗 更新时间:2023-10-29 13:30:30 26 4
gpt4 key购买 nike

我有这个:

Comparator<Item> ignoreLeadingThe = new Comparator<Item>() {
public int compare(Item a, Item b) {
String newA = a.name.replaceAll("(?i)^the\\s+", "");
String newB = b.name.replaceAll("(?i)^the\\s+", "");
return newA.compareToIgnoreCase(newB);
}
};

Array.sort(MyItemArrayOfObjects, ignoreLeadingThe);

我停止使用数组,现在使用 ArrayList。所以当我这样做时:

Collections.sort(MyItemArrayListOfObjects, ignoreLeadingThe);

我什至无法弄清楚它现在排序所依据的模式。我可以像这样做一个干净的开关吗? (完全有可能我用上面没有提到的东西打破了这个,如果这是正确的,那么这就是我需要知道的)

注意:最初,对于数组,我只是试图按字母顺序排列列表并忽略前导“The”。它适用于 Android 应用程序。每个列表行项目数据都包装在我传递给 ArrayAdapter 的对象中。我只是想在该对象中获取一个 ArrayList 并将其按字母顺序排列。所以本质上,它是一个 ArrayList,其中包含一些 ArrayList。

最佳答案

对于 Collections.sort 来说效果很好,我只建议改进比较器

    Comparator<Item> ignoreLeadingThe = new Comparator<Item>() {
Pattern pattern = Pattern.compile("(?i)^the\\s+");
public int compare(Item a, Item b) {
String newA = pattern.matcher(a.name).replaceAll("");
String newB = pattern.matcher(b.name).replaceAll("");
return newA.compareToIgnoreCase(newB);
}
};

关于java - 从排序对象数组到 ArrayList<Object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16006003/

26 4 0