[英]How to sort String array by length using Arrays.sort()
我正在尝试使用Arrays.sort()
根据字符串的长度对字符串数组进行排序,但这会按字典顺序而不是按长度对字符串进行排序。 这是我的代码:
S = "No one could disentangle correctly"
String W[] = S.split(" ");
Arrays.sort(W);
排序后:
correctly
could
disentangle
no
one
但我想要的是
no //length = 2
one //length = 3
could //length = 4 and likewise
correctly
disentangle
怎么才能得到上面的output? 请给出 JDK 1.7 & JDK1.8 的答案。
java 8 及以上
Arrays.sort(W, (a, b)->Integer.compare(a.length(), b.length()));
更简洁的方法是使用Mano 的答案中的 Comparator.comparingInt 。
替代 matt 的版本并且比 matt 的版本稍微简单一些
Arrays.sort(W, Comparator.comparingInt(String::length));
如果您使用的是JDK 1.8 或更高版本,则可以使用lambda 表达式,如matt answer。 但是,如果您使用的是JDK 1.7 或更早版本,请尝试编写一个自定义比较器,如下所示:
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
}
});
只需更改参数 position 我们就可以按降序排序。
Arrays.sort(W, (a,b)->b.length() - a.length());
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
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
}
}
我的回答与这个问题有点无关(我想排序,而不是数组),但由于这里提供的答案帮助我解决了我的错误,我将把它留在这里给那些面临问题的人。
Collections.sort(vehicles, (VehiclePayload vp1, VehiclePayload vp2)
-> Integer.compare(vp2.getPlateNumber().length(), vp1.getPlateNumber().length()));
//可能但不推荐;
String sp[]="No one could disentangle correctly".split(" ");
for(int i=0;i<sp.length-1;i++)
{
for(int j=i+1;j<sp.length;j++)
{
if(sp[i].length()>sp[j].length())
{
String temp=sp[i];
sp[i]=sp[j];
sp[j]=temp;
}
}
}
for(String i:sp) //will print content of array sp
System.out.println(i);
如果您更喜欢 Java8 以后的 Streams,那么您可以使用 -
String input = "This is a beautiful world";
String[] arr = Arrays.stream(input.split(" "))
.sorted(Comparator.comparingInt(String::length))
.toArray(String[]::new);
// prints output
System.out.println(Arrays.toString(arr));
output 是 -
[a, is, This, world, beautiful]
ArrayList<String> list=new ArrayList<>();
list.add("diamond");
list.add("silver");
list.add("gold");
System.out.println(list.stream().sorted(Comparator.comparingInt(String::length)).collect(Collectors.toList()));
output:
[gold, silver, diamond]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.