简体   繁体   English

使用Collections.sort对字符串进行排序?

[英]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. 我正在尝试使用collection.sort()方法对两个字符串进行排序,但是我在理解实现的逻辑时遇到了问题。 Here is what I have so far. 这是我到目前为止所拥有的。 Are there any issues with my implementation? 我的实施有问题吗? Note: I want to sort them alphabetically: "Apple" > "Orange" 注意:我想按字母顺序对它们进行排序:“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 . String实现了一个Comparable<String> ,它实现为字典比较,换句话说,默认为"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有一个变量,它将这个比较器考虑在内,你可以简单地使用:

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. 你不应该使用String.valueofString.valueof转换为字符串:你可以将char< s进行比较,但是你不能在String上使用这个运算符。 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" . 此外,您的实现不是递归的 :如果两个第一个字符相等,那并不意味着String 本身是相等的,例如"Apple""Ambiguous" So you would have to implement a more complex comparator. 所以你必须实现一个更复杂的比较器。

You can't compare String with the symbol > . 您无法将String与符号>进行比较。 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 . 如果要以词法方式对整个字符串值进行排序,那么您可以简单地使用Collections.sort(mailbox.getMessages())因为String已经实现了Comparable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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