Java,特殊排序一个ArrayList,末尾有更长的条目

M4t*_*X3r 5 java sorting android arraylist

我有一个ArrayList<String>Java.现在我想用一些要求对它进行排序.

我在ArrayList中有这些项目,例如:

xyz
bcd
abc_locked
cde
efg_locked
fgh
Run Code Online (Sandbox Code Playgroud)

我想在最后推回那些_locked并保持秩序,这样做:

xyz
bcd
cde
fgh
abc_locked
efg_locked
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?我是否必须遍历List才能删除String并再次添加它?或者,还有更好的方法?

Roh*_*ain 5

您可以尝试使用此比较器:

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);
Run Code Online (Sandbox Code Playgroud)