Java 如何使用 Arrays.sort() 按长度对字符串数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35866240/
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 to sort String array by length using Arrays.sort()
提问by Zohra Khan
I am trying to sort an array of strings according to their length using Arrays.sort()
, but this sorts the strings lexicographically rather than by length. Here is my code:
我正在尝试使用根据字符串的长度对字符串数组进行排序Arrays.sort()
,但这会按字典顺序而不是按长度对字符串进行排序。这是我的代码:
S = "No one could disentangle correctly"
String W[] = S.split(" ");
Arrays.sort(W);
After sorting :
排序后:
correctly
could
disentangle
no
one
but what I want is
但我想要的是
no //length = 2
one //length = 3
could //length = 4 and likewise
correctly
disentangle
How can I get the above output? Please give answer for JDK 1.7 & JDK1.8.
我怎样才能得到上面的输出?请给出 JDK 1.7 和 JDK1.8 的答案。
采纳答案by mmuzahid
If you are using JDK1.8 or above then you could use lambda expressionlike mattanswer. But if you are using JDK1.7 or earlier version try to write a custom Comparatorlike this:
如果您使用的是JDK1.8 或更高版本,那么您可以使用像mattanswer这样的lambda 表达式。但是,如果您使用的是JDK1.7 或更早版本,请尝试编写这样的自定义 Comparator:
String S = "No one could disentangle correctly";
String W[] = S.split(" ");
Arrays.sort(W, new java.util.Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparision
}
});
回答by matt
For java 8 and above
对于 java 8 及以上
Arrays.sort(W, (a, b)->Integer.compare(a.length(), b.length()));
A more concise way is to use Comparator.comparingInt from Mano's answerhere.
更简洁的方法是使用Mano 的答案中的Comparator.comparingInt 。
回答by Manos Nikolaidis
Alternative to and slightly simpler than matt's version
替代并比 matt 的版本稍微简单
Arrays.sort(W, Comparator.comparingInt(String::length));
回答by Vikrant Kashyap
import java.util.*;
class SortStringArray
{
public static void main (String[] args) throws java.lang.Exception
{
String S = "No one could disentangle correctly";
String W[] = S.split(" ");
Arrays.sort(W, new StringLengthComparator());
for(String str: W)
System.out.println(str); //print Your Expected Result.
}
}
class StringLengthComparator implements Comparator<String>{ //Custom Comparator class according to your need
@Override
public int compare(String str1, String str2) {
return str1.length() - str2.length();// compare length of Strings
}
}
回答by Abhijeet Gupta
Simply changing the parameter position we can sort in descending order.
只需更改参数位置,我们就可以按降序排序。
Arrays.sort(W, (a,b)->b.length() - a.length());
回答by Varun
Java 8 is pretty easy. as mentioned in the above answer. I was solving some problems on hackerrank and there they are using java 7. so I had to write the java7. That is selection sort. though time complexity is not great O(n^2) however it serves the purpose.
Java 8 非常简单。如上面的答案所述。我正在解决hackerrank上的一些问题,他们正在使用java 7。所以我不得不编写java7。那就是选择排序。虽然时间复杂度不是很大 O(n^2) 但它可以达到目的。
public static void main(String[] args) {
// I am taking list and again converting to array. please ignore. you can directly take array of string and apply the logic.
List<String> listOfString = new ArrayList<String>();
listOfString.add("because");
listOfString.add("can");
listOfString.add("do");
listOfString.add("must");
listOfString.add("we");
listOfString.add("what");
String[] w= new String[listOfString.size()];
for(int i =0;i <listOfString.size();i++) {
w[i] = listOfString.get(i);
}
// That is for java 8
//Arrays.sort(w, (a, b)->Integer.compare(a.length(), b.length()));
for (int i = 0; i < w.length; i++) {
for(int j=i+1;j<w.length;j++) {
String tempi = w[i];
String tempj = w[j];
if(tempj.length()<tempi.length()) {
w[i] =w[j];
w[j]=tempi;
}
}
}
// That is for printing the sorted array
for (int i = 0; i < w.length; i++) {
System.out.println(w[i]);
}
Output.
输出。
do
we
can
must
what
because