首页 > 解决方案 > 使用完全自定义的多个规则对字符串列表进行排序

问题描述

我有一个这样的字符串列表:[8****, 7****, 73***, ****1, **101, *4101, 12010 etc]

我想用以下两条规则进行排序。

所以最终的数组应该变成:[7****, 8****, 73***, 320**, ****1, **101, 12101]

我创建了一个自定义比较器,并单独获取每个字符:

public class MyCustomComparator implements Comparator<ObjToCompare> {


@Override
public int compare(ObjToCompare o1, ObjToCompare o2) {


    String lastSubstr1 = o1.getMyString.substring(o1.getMyString.length()-1);
    String lastSubstr2 = o2.getMyString.substring(o2.getMyString.length()-1);

    String secondFromLastSubstr1 =o1.getMyString.substring(o1.getMyString.length()-2,o1.getMyString().length()-1);
    String secondFromLastSubstr2 =o2.getMyString.substring(o2.getMyString.length()-2,o2.getMyString().length()-1);

    String thirdFromLastSubstr1 = o1.getMyString.substring(o1.getMyString.length()-3,o1.getMyString().length()-2);
    String thirdFromLastSubstr2 = o2.getMyString.substring(o2.getMyString.length()-3,o2.getMyString().length()-2);

    String fourthFromLastSubstr1 = o1.getMyString.substring(o1.getMyString.length()-4,o1.getMyString().length()-3);
    String fourthFromLastSubstr2 = o2.getMyString.substring(o2.getMyString.length()-4,o2.getMyString().length()-3);

    String fifthFromLastSubstr1 = o1.getMyString.substring(o1.getMyString.length()-5,o1.getMyString().length()-4);
    String fifthFromLastSubstr2 = o2.getMyString.substring(o2.getMyString.length()-5,o2.getMyString().length()-4);




    int last =  lastSubstr1.compareTo(lastSubstr2);



    return lastSubstr1.compareTo(lastSubstr2);
}}

如何实现上述逻辑?非常感谢您提前。

标签: javacomparator

解决方案


我会这样做:创建两个Strings (用于两个规则)。每个String按规则设置的顺序保存字符。例如:

String rule1Order = "*1234567890";

现在字符串中字符的索引可以看作是数字顺序值。索引之间的差异是期望的compareTo结果:

int lastSubstr1Ordervalue = rule1Order.indexOf(lastSubstr1); 
int lastSubstr2Ordervalue = rule1Order.indexOf(lastSubstr2); 
int lastSubstrCompareTo = lastSubstr1Ordervalue - lastSubstr2Ordervalue; 

推荐阅读