Java 如何按字典顺序对 ArrayList 进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2999129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I sort an ArrayList lexicographically?
提问by Jake
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?
我正在尝试对表示卡值的字符串 ArrayList 进行排序。因此,有些卡片包含字母(“King”),有些卡片包含仅包含数字(“7”)的字符串。我知道使用 Collections.sort,但它只对包含字母的字符串进行排序。如何让 ArrayList 按数字和字母顺序排序?
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
编辑:对不起,我在看排序时一定没有太注意。排序工作正常,我一定是因为 10 将在 2 之前出现这一事实而被抛弃。谢谢
回答by Jon Skeet
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".
不,Collections.sort
将使用 Unicode 序数词典比较对所有内容进行排序,因为这是String.compareTo
. “7”将在“King”之前,“10”将在“2”之前。
回答by OscarRyz
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?
我知道使用 Collections.sort,但它只对包含字母的字符串进行排序。如何让 ArrayList 按数字和字母顺序排序?
If the string is a number it is already being sorted ( as an String though ) look:
如果字符串是一个数字,它已经被排序(虽然作为一个字符串)看起来:
import java.util.*;
class Sort {
public static void main( String [] args ) {
List list = Arrays.asList("Kings","7", "Abcd", "3.1416");
Collections.sort( list );
System.out.println( list );
}
}
Prints
印刷
$ java Sort
[3.1416, 7, Abcd, Kings]
Is that what you need?
那是你需要的吗?
edit
编辑
Assuming ( guessing ) what you need is to sort a deck of cards, which have both numbers and "letters" ( J, Q, K, A ) you may try to use a custom comparator.
假设(猜测)您需要对一副牌进行排序,其中有数字和“字母”(J、Q、K、A),您可以尝试使用自定义比较器。
Here's one that takes into consideration the numbers "as numbers" the the rest as strings, so "10" comes after "2" but before "Kings"
这是一个将数字“作为数字”考虑在内的其他字符串,因此“10”在“2”之后但在“Kings”之前
import java.util.*;
class Sort {
public static void main( String [] args ) {
List<String> list = Arrays.asList("Kings","7", "Queen", "3", "10", "A", "2", "8", "Joker");
Collections.sort( list , new Comparator<String>(){
public int compare( String a, String b ){
// if both are numbers
if( a.matches("\d+") && b.matches("\d+")) {
return new Integer( a ) - new Integer( b );
}
// else, compare normally.
return a.compareTo( b );
}
});
System.out.println( list );
}
}
$ java Sort
[2, 3, 7, 8, 10, A, Joker, Kings, Queen]
If that's what you need I guess this would help you to figure out the rest. Probably the next thing would be how to sort spades vs. hearts.
如果这就是你所需要的,我想这会帮助你弄清楚其余的。接下来的事情可能是如何对黑桃和红桃进行排序。
Following the answer by Romanyou could create a class and implement the Comparableinterface:
按照Roman的回答,您可以创建一个类并实现Comparable接口:
class Card implements Comparable<Card> {
public int compareTo( Card other ) {
// add custom logic to compare one card with other
}
}
回答by Sanjay Manohar
Sort will sort everything according to your charset. In otherwords, all numbers will come before letters in the lexicographic order. For example, decimal numbers start with a '.' and out of order lexicographically.
Sort 将根据您的字符集对所有内容进行排序。换句话说,所有数字都将出现在字典顺序中的字母之前。例如,十进制数以“.”开头。并且按字典顺序乱序。
If you want to change this, make Comparator object. You could then put the items in whatever order you like.
如果要更改此设置,请创建 Comparator 对象。然后,您可以按您喜欢的任何顺序放置这些项目。
For example, this will sort numbers in numerical order, and also words in lexical order:
例如,这将按数字顺序对数字进行排序,并按词汇顺序对单词进行排序:
class CardComparator extends Object implements Comparator{
public int compare(Object a, Object b){
try{
double d1=Double.valueOf(a.toString());
try{
double d2=Double.valueOf(b.toString());
return (d2>d1)?1:-1; // both numeric
}catch(NumberFormatException e){ // a is numeric but b isn't
return 1;
}
}catch(NumberFormatException e){
try{
double d2=Double.valueOf(b.toString());
return -1; // a is nonnumeric but b is
}catch(NumberFormatException e){ // both nonnumeric
return a.toString().compareTo(b.toString);
}
}
}
}
Comparator comparator=new CardComparator();
Collections.sort(cards, comparator);
PS not tested!
PS未测试!
回答by Pops
As @Jon Skeet said, the built-in sort will compare based on Unicode values. You'd have to write your own sorting method.
正如@Jon Skeet 所说,内置排序将基于 Unicode 值进行比较。您必须编写自己的排序方法。
As long as you're writing your own code, though, might I suggest an enumeration? A deck of cards is one of the canonical examples for use of enums. The short version is that you can declare your own sort order for a group of things; you could even make the king of spades outrank the king of diamonds, if you wanted. Check out Sun's tutorial here.
但是,只要您编写自己的代码,我可以建议枚举吗?一副纸牌是使用枚举的典型例子之一。简而言之,您可以为一组事物声明自己的排序顺序;如果你愿意,你甚至可以让黑桃之王的等级超过钻石之王。在此处查看 Sun 的教程。
回答by Roman
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.
据我了解,您有一个类似的数组,["7", "Queen", "9", "6"]
并且希望它["Queen", "9", "7", "6"]
在排序完成后看起来像(或以相反的顺序)。
I'd recommend to make it a bit more object-oriented i.e. create class Card with fields name and value:
我建议让它更加面向对象,即创建具有字段名称和值的类 Card:
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.
之后,使用字段value
而不是卡片的名称对卡片进行所有操作(尤其是排序)会容易得多。