Sort a list of String with completely custom multiple rules

Filip123go :

I have an List of strings like this: [8****, 7****, 73***, ****1, **101, *4101, 12010 etc]

And I want to sort with the following 2 rules.

  • First rule: Using only the last number / asterisks , the sorted should be: first asterisks, then numbers 1-9 and then 0.
  • Second rule: Using the second from last character the sorting should be: first asterisks , then numbers 0-9.

so the final array should become : [7****, 8**** , 73***, 320** , ****1 , **101, 12101]

I have created a custom Comparator and I get each char individually:

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);
}}

How can I implement the above logic? Thank you very much in advance.

Sharon Ben Asher :

Here's how I would do it: create two Strings (for the two rules). each String holds the characters in the order set by the rule. For example:

String rule1Order = "*1234567890";

now the index of the character in the String can be regarded as numeric order value. the difference between the indexes is the desired compareTo result:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=356534&siteId=1