简体   繁体   中英

Sort an array of strings based on length in ascending order

The question is to print the array of string in accordance with the length of strings in ascending order.

For example

input={"vellore","i","from","am"}
output=i am from vellore

Here is my code:

int n=sc.nextInt();
    sc.nextLine();
    String[] arr = new String[n];
    for(int i=0;i<n;i++){
        arr[i]=sc.nextLine();
    }
    //System.out.println(Arrays.toString(arr));
    Arrays.sort(arr);
    for(String i: arr){
        System.out.print(i+" ");
    }

Now I know that my output will come in lexical order that is as "am from i vellore", but I want to get my desired output using sort method. I tried using Collections.sort() as well by using arraylist but I still didn't get my desired output.

I want to get my output using sort method without using the normal approach by comparing the lengths of string and all.

You want a Comparator . In this case, you specifically want to start by comparing the String lengths. I would suggest you then compare naturally (to break ties). Like,

String[] arr = { "vellore", "i", "from", "am" };
Arrays.sort(arr, Comparator.comparingInt(String::length)
        .thenComparing(Comparator.naturalOrder()));
System.out.println(Arrays.toString(arr));

Outputs (as requested)

[i, am, from, vellore]

tl;dr

Comparator
.comparingLong( ( String s ) -> s.codePoints().count() )
.thenComparing( Comparator.naturalOrder() )

Avoid legacy type char

The Answer by Frisch is correct in suggesting the use of a Comparator . However, the method reference seen there, String::length , fails with most characters. See this example . The String#length method reports a two-character string like c as three, incorrectly.

The failure is because that method depends on char which has been legacy since Java 2. As a 16-bit value, the char type is physically incapable of representing most of the over 140,000 characters defined in a Unicode.

Code points

Instead, use Unicode code point integers.

Switch out that method reference for the use of code points rather than char type.

Here we use String#codePoints to generate an IntStream . That IntStream is a stream of each character's code point number, a value in the range of zero to just over a million. Then we use IntStream#count to get a count of the values in that stream, a count of the characters in the original string.

    String[] arr = { "a1", "c🕒", "b2", "d4" };
    Arrays
        .sort(
            arr , 
            Comparator
            .comparingLong( ( String s ) -> s.codePoints().count() )
            .thenComparing( Comparator.naturalOrder() )
        );
    System.out.println( Arrays.toString( arr ) );

See that code run live at IdeOne.com .

[a1, b2, c, d4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM