List an Array of Strings in alphabetical order

前端 未结 11 1440
独厮守ぢ
独厮守ぢ 2020-12-28 14:49

I have a program which has the user inputs a list of names. I have a switch case going to a function which I would like to have the names print off in alphabetical order.

11条回答
  •  [愿得一人]
    2020-12-28 15:05

    By alphabetical-order I assume the order to be : A|a < B|b < C|c... Hope this is what @Nick is(or was) looking for and the answer follows the above assumption.

    I would suggest to have a class implement compare method of Comparator-interface as :

    public int compare(Object o1, Object o2) {
        return o1.toString().compareToIgnoreCase(o2.toString());
    }
    

    and from the calling method invoke the Arrays.sort method with custom Comparator as :

    Arrays.sort(inputArray, customComparator);
    

    Observed results: input Array : "Vani","Kali", "Mohan","Soni","kuldeep","Arun"

    output(Alphabetical-order) is : Arun, Kali, kuldeep, Mohan, Soni, Vani

    Output(Natural-order by executing Arrays.sort(inputArray) is : Arun, Kali, Mohan, Soni, Vani, kuldeep

    Thus in case of natural ordering, [Vani < kuldeep] which to my understanding of alphabetical-order is not the thing desired.

    for more understanding of natural and alphabetical/lexical order visit discussion here

提交回复
热议问题