Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort an ArrayList lexicographically?

I am trying to sort an ArrayList of Strings that represent card values. So, some cards contain letters ("King") and some contain Strings containing only a number ("7"). I know to use Collections.sort, but it only sorts Strings that contain letters. How do I get the ArrayList to be sorted by number as well as alphabetically?

Edit: Sorry, I must not have been paying much attention when I looked at the sorting. The sort works correctly, I must have just been thrown off by the fact that a 10 will come before a 2. Thanks

like image 312
Jake Avatar asked Jun 08 '10 16:06

Jake


2 Answers

No, Collections.sort will sort everything, using an Unicode ordinal lexicographic comparison as that's the behaviour of String.compareTo. "7" will come before "King", and "10" will come before "2".

like image 94
Jon Skeet Avatar answered Sep 17 '22 13:09

Jon Skeet


As I understand, you have an array like ["7", "Queen", "9", "6"] and you want it to look like ["Queen", "9", "7", "6"] (or in reverse order) after sorting is done.

I'd recommend to make it a bit more object-oriented i.e. create class Card with fields name and value:

class Card {
   private final String name;
   private final int value;
   ...
   //constructor and getters
}

and after that create instances in this manner:

Card six = new Card("6", 6);
Card ten = new Card("10", 10);
Card queen = new Card("Queen", 12);

After that it'll be much easier to make all operations with cards (and sorting particularly) using field value instead of cards' names.

like image 27
Roman Avatar answered Sep 17 '22 13:09

Roman