如何使用Arrays.sort()按长度排序String数组

时间:2016-03-08 11:33:03

标签: java arrays

我正在尝试使用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

但我想要的是

// Document Ready() Starts

$("#grid_id").jqGrid({
                url :"search/getHouseholdHistoryList",
                async : false,
                type: 'GET',
                datatype: 'json',
                postData: {
                    searchHHID: function() { return $("#txt_SearchID").val(); },
                    filterKey:  function() { return $('#ulSearch_TypeOfID li.selected').attr('value') }
                },
                colNames:mainGridColNames,
                colModel: [
                    { name:'incidentID', index:'incidentID', width:110,sortable:true},
                    { name:'incidentCreatedDate', index:'incidentCreatedDate', width:160, sortable:false},
                    { name:'incidentSummary', index:'incidentSummary', width:482,sortable:false},
                    { name:'incidentStatus', index:'incidentStatus', width:120, sortable:false},
                    { name:'actionLink', index:'actionLink', width:100, sortable:false}
                ],
                viewrecords: true,
                //autowidth:true,
                width: '100%',
                height:'150',
                rowNum: 10,
                rowList:[10,20,30], 
                rownumbers: false,
                sortorder: "desc",
                ignoreCase: true,
                loadonce: true,
                jsonReader: { repeatitems: false },
                pager: 'gridpager',
                direction:'ltr'
            }).jqGrid('navGrid','gridpager',
                      {edit:false, add:false, del:false, search:true, refresh:true});

//Document Ready() Ends

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

6 个答案:

答案 0 :(得分:22)

>>> help(a_method)

答案 1 :(得分:15)

替代和稍微简单比亚光的版本

Arrays.sort(W, Comparator.comparingInt(String::length));

答案 2 :(得分:6)

如果您使用 JDK 1.8或更高版本,那么您可以使用 lambda表达,例如 matt 回答。但是,如果您使用 JDK 1.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
    }
});

答案 3 :(得分:1)

只需更改参数位置,我们就可以按降序排序。

Arrays.sort(W, (a,b)->b.length() - a.length());

答案 4 :(得分:1)

Java 8非常简单。如上述答案所述。 我在hackerrank上解决了一些问题,并且那里使用的是Java7。所以我不得不编写java7。 那就是选择排序。尽管时间复杂度不是很高,但O(n ^ 2)可以达到目的。

int main() {
    Car Car;
    int i = 1;
    Car.fuel = 200;
    Car.speed = 10.2;

    //Example with lambda function.
    SetInterval(Car,[&](struct Car){
        Car.speed += 1.9;
        Car.fuel -= 1.2;
        cout << Car.speed << " " << Car.fuel << endl;
        }, 900, 10); // it will end after 10 calls with 0.9 sec interval
     //Second Example, wich not working
    SetInterval(i, [&](int i){ i++; cout << i << endl;}, 500, 5);
}

输出。

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

答案 5 :(得分:0)

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