java - Sorting Strings using Collections.sort? -
java - Sorting Strings using Collections.sort? -
i'm attempting sort 2 strings using collection.sort() method, i'm having issues understanding logic of implementation. here have far. there issues implementation? note: want sort them alphabetically: "apple" > "orange"
collections.sort(mailbox.getmessages() , (string a, string b) -> { if (string.valueof(a.charat(0)) > string.valueof(b.charat(0))) { homecoming -1; } else if (string.valueof(a.charat(0)) < string.valueof(b.charat(0))) { homecoming 1; } else { homecoming 0; } });
string
implements comparable<string>
implemented lexicographical comparison, in other words, default "apple".compareto("orange") < 0
. default sufficient.
now collections.sort
has variant takes comparator account, can use:
collections.sort(mailbox.getmessages());
about own implementation:
you shouldn't utilize string.valueof
cast string: can compare char
s <
, can't utilize operator on string
s. furthermore implementation not recursive: if 2 first characters equal, doesn't mean string
's equal per se, instance "apple"
, "ambiguous"
. have implement more complex comparator.
java string sorting
Comments
Post a Comment