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 chars <, can't utilize operator on strings. 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

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -