简体   繁体   中英

Sorting Strings using Collections.sort?

I'm attempting to sort two strings using the collection.sort() method, but I'm having issues understanding the logic of the implementation. Here is what I have so far. Are there any issues with my implementation? Note: I want to sort them alphabetically: "Apple" > "Orange"

Collections.sort(mailbox.getMessages() , (String a, String b) -> {
    if (String.valueOf(a.charAt(0)) > String.valueOf(b.charAt(0))) {
        return -1;
    }
    else if (String.valueOf(a.charAt(0)) <
        String.valueOf(b.charAt(0))) {
        return 1;
    }
    else {
        return 0;
    }
});

String implements a Comparable<String> which is implemented as a lexicographical comparison, in other words, by default "Apple".compareTo("Orange") < 0 . So the default is sufficient.

Now Collections.sort has a variant that takes this comparator into account, you can thus simply use:

Collections.sort(mailbox.getMessages());

About your own implementation:

You shouldn't use String.valueof to cast back to a string: you can compare char s with the < , but you can't use this operator on String s. Furthermore your implementation is not recursive : if the two first characters are equal, that doesn't mean the String 's are equal per se , for instance "Apple" and "Ambiguous" . So you would have to implement a more complex comparator.

You can't compare String with the symbol > . You can simply do :

Collections.sort(mailbox.getMessages(), (String a, String b) -> {
     return Character.compare(a.charAt(0), b.charAt(0));
});

Note that this will sort according only to first character. If you want to sort on the entire string value lexographically then you can simply use Collections.sort(mailbox.getMessages()) as String already implements Comparable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM