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?
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);
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
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With