Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, special sort an ArrayList with longer entries at the end

I have an ArrayList<String> in Java. Now I want to sort it with some requirements.

I have these items in the ArrayList for example:

xyz
bcd
abc_locked
cde
efg_locked
fgh

And I want to push back the ones with _locked at the end and keep the order, to make this:

xyz
bcd
cde
fgh
abc_locked
efg_locked

What is the best way to do this? Would I have to iterate through the List remove the String and just add it again? or is there a better way?

like image 602
M4tchB0X3r Avatar asked Jun 27 '13 12:06

M4tchB0X3r


2 Answers

You can try using this comparator:

Comparator<String> comparator = new Comparator<String>() {

     @Override
     public int compare(String arg1, String arg2) {

         if (arg1.matches("^.*_locked$") && arg2.matches("^.*_locked$")) {
             // Both string have _locked at the end. Retain the order.
             return 0;
         } else if (arg1.matches("^.*_locked$")) {
             // First string have _locked. Swap.
             return 1;
         } else if (arg2.matches("^.*_locked$")) {
             // Second string have _locked. No need to swap
             return -1;
         } 

         // None of the string have _locked. Retain the order
         return 0;

     }
};

Collections.sort(list, comparator);
like image 63
Rohit Jain Avatar answered Oct 01 '22 13:10

Rohit Jain


Use a comparator:

Collections.sort(list, new Comparator(){
    public int compare(String o1, String o2) {
        if ((o1.endsWith("_locked")&&(!o2.endsWith("_locked"))){
            return 1;
        }
        else if (!(o1.endsWith("_locked")&&(o2.endsWith("_locked"))){
            return 1;
        }
        else {
            //Fallback sorting based on start of string left as exercise to reader
        }
    }

});
like image 28
nanofarad Avatar answered Oct 01 '22 13:10

nanofarad