gpt4 book ai didi

java - 使用预定义顺序对 java arrayList 进行排序

转载 作者:搜寻专家 更新时间:2023-10-31 19:58:14 24 4
gpt4 key购买 nike

我有一个未排序的列表,但我想以自定义方式排序,即

item_one_primary.pls
item_one_secondary.pls
item_one_last.pls

item_two_last.pls
item_two_primary.pls
item_two_secondary.pls

item_three_secondary.pls
item_three_last.pls
item_three_primary.pls

这是我预定义的顺序:primary, secondary, last

应用排序后的无序列表应该如下所示:

item_one_primary.pls
item_one_secondary.pls
item_one_last.pls

item_two_primary.pls
item_two_secondary.pls
item_two_last.pls

item_three_primary.pls
item_three_secondary.pls
item_three_last.pls

我尝试了一些比较器,但结果是这样的:

item_one_primary.pls
item_two_primary.pls
item_three_primary.pls

...

有谁知道如何对此进行排序?

这是我用过的一些代码:

List<String> predefinedOrder;

public MyComparator(String[] predefinedOrder) {
this.predefinedOrder = Arrays.asList(predefinedOrder);
}

@Override
public int compare(String item1, String item2) {
return predefinedOrder.indexOf(item1) - predefinedOrder.indexOf(item2);
}

我没有包含拆分(首先用点 (.) 拆分,然后用下划线 (_) 拆分以获得预订列表中的项目)。

最佳答案

您必须使用一个比较器,它首先检查商品编号,只有当它们相等时,才检查您的预定义顺序

尝试这样的事情:

public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;

String[] a1 = s1.split("_");
String[] a2 = s2.split("_");

/* If the primary elements of order are equal the result is
the order of the second elements of order */
if (a1[1].compareTo(a2[1]) == 0) {
return a1[2].compareTo(a2[2]);
/* If they are not equal, we just order by the primary elements */
} else {
return a1[1].compareTo(a2[1]);
}
}

这只是一个基本示例,一些额外的错误检查会很好。

关于java - 使用预定义顺序对 java arrayList 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5807309/

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