java 在Java中首先按长度然后按字母顺序对数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3408976/
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
Sort array first by length then alphabetically in Java
提问by Brian
How can I sort an array first by length, then alphabetically?
如何首先按长度对数组进行排序,然后按字母顺序排序?
I have a list of things with numbers on them, and I am currently getting:
我有一个带有数字的东西的清单,我目前得到:
Something1 Something10 Something2 Something3
某物1 某物10 某物2 某物3
Whereas I want to get:
而我想得到:
Something1 Something2 Something3 Something10
某事1某事2某事3某事10
回答by KeatsPeeks
public class MyComparator implements Comparator<String>{
@Override
public int compare(String o1, String o2) {
if (o1.length() > o2.length()) {
return 1;
} else if (o1.length() < o2.length()) {
return -1;
}
return o1.compareTo(o2);
}
}
Then use:
然后使用:
Collections.sort(yourList, new MyComparator());
回答by Lukas Eder
Here's a concise Java 8 solution:
这是一个简洁的 Java 8 解决方案:
List<String> list = Arrays.asList("Something1", "Something10", "Something2", "Something3");
list.sort(Comparator.comparing(String::length).thenComparing(String::compareTo));
Or, case-insensitive version:
或者,不区分大小写的版本:
list.sort(Comparator.comparing(String::length).thenComparing(String::compareToIgnoreCase));
回答by Peter Lawrey
Create a Comparator which compares by length first and if the lengths are the same, uses the String.compareTo().
创建一个比较器,首先按长度进行比较,如果长度相同,则使用 String.compareTo()。
回答by Jim Garrison
Sorting first by length and then lexically will work ONLY if the string prefixes (i.e. the part before the number) is the same length in all cases. I believe you may really want to write a comparator that separates the string and numeric parts and sorts alphabetically on the string and numerically on the number part.
仅当字符串前缀(即数字之前的部分)在所有情况下长度相同时,首先按长度排序,然后按词法排序才有效。我相信您可能真的想编写一个比较器来分隔字符串和数字部分,并在字符串上按字母顺序排序,在数字部分上按数字排序。
回答by Starkey
Define a class to hold your item in. Seems like you want it to be a String.
定义一个类来保存您的项目。似乎您希望它是一个字符串。
For that class, you need to define the Comparable interface and put the logic to compare in its abstract method.
对于该类,您需要定义 Comparable 接口并将要比较的逻辑放在其抽象方法中。
int compareTo(T o)
For example:
例如:
class MyString extends String
{
@Override
int compareTo(Object obj)
{
// put your logic in here.
// Return -1 if this is "less than" obj.
// Return 0 if this is equal to obj
// Return 1 if this is "greater than" obj.
// Test length first
if (length() < obj.length())
return -1;
if (length() > obj.length())
return 1;
// Lengths are the same, use the alphabetical compare defined by String already
return super.compareTo(obj);
}
}
Disclaimer, I didn't actually test this code, but it should be close to what you want.
免责声明,我实际上并没有测试这段代码,但它应该接近你想要的。

