如何使用Arrays.sort()按长度排序String数组 [英] How to sort String array by length using Arrays.sort()

查看:560
本文介绍了如何使用Arrays.sort()按长度排序String数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Arrays.sort()根据长度对字符串数组进行排序,但是这会按字典顺序而不是按长度对字符串进行排序。这是我的代码:

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:

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

如何获得上述输出?请给出JDK 1.7&的回答。 JDK1.8。

How can I get the above output? Please give answer for JDK 1.7 & JDK1.8.

推荐答案

如果您使用 JDK 1.8或更高版本,那么您可以使用 lambda表达式,如 matt 回答。但是,如果您使用 JDK 1.7或更早版本,请尝试编写自定义Comparator ,如下所示:

If you are using JDK 1.8 or above then you could use lambda expression like matt answer. But if you are using JDK 1.7 or earlier version try to write a custom Comparator like this:

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
    }
});

这篇关于如何使用Arrays.sort()按长度排序String数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆