Skip to content

Instantly share code, notes, and snippets.

@uOOOO
Created June 20, 2019 08:21
Show Gist options
  • Select an option

  • Save uOOOO/8880997d37a4bd08c0b4e73aa00e5cf4 to your computer and use it in GitHub Desktop.

Select an option

Save uOOOO/8880997d37a4bd08c0b4e73aa00e5cf4 to your computer and use it in GitHub Desktop.
Example comparing strings not lexicographically
void sortList(@SuppressWarnings("SameParameterValue") final boolean isAsc, List<String> contentItems) {
Collections.sort(contentItems, new Comparator<String>() {
@Override
public int compare(String str1, String str2) {
if (str1 == null || str2 == null) {
return 0;
}
//noinspection StringEquality
if (str1 == str2) {
return 0;
}
for (int i = 0; i < str1.length() && i < str2.length(); i++) {
char c1 = str1.charAt(i);
char c2 = str2.charAt(i);
if (str1.length() != str2.length() && (i == str1.length() - 1 || i == str2.length() - 1)) {
return isAsc? str1.length() - str2.length() : str2.length() - str1.length();
}
if (c1 < c2) {
return isAsc ? -1 : 1;
} else if (c1 > c2) {
return isAsc ? 1 : -1;
}
}
return 0;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment