John Doe John Doe - 2 months ago 16
Java Question

How to sort 2D String array by the number of elements in java

I know that this may be an easy question,but I could not come up with an appropriate algorithm. I have an 2d array of strings and I would like to sort it by the number of elements: Assuming the array is as follows:

public class arraysort

{

public static void main(String[] args)

{
String[][] terms = {{"java", "php", "ruby", "csharp", "dotnet", "perl"},
{"google", "apple", "oracle", "microsoft", "sun"},
{"http", "web", "dns", "net", "protocol", "packet","ip"},
{"london","madrid","berlin","ankara","astana"}};



}
}


How can I get sorted array by the number of elements in this way(5,5,6,7):

[google, apple, oracle, microsoft, sun]
[london, madrid, berlin, ankara, astana]
[java, php, ruby, csharp, dotnet, perl]
[http, web, dns, net, protocol, packet, ip]


Also, it is interesting for me, what happens when the number of elements is equal in each group such as "google" and "london" groups have equal number of elements. Thank you for your help!

Answer

Use java.util.Arrays.sort(...) (the Arrays class API link). One of the method overloads takes an array parameter with a Comparator parameter, in in your Comparator's compare(...) method, compare the lengths of the sub arrays.

e.g.,

Arrays.sort(terms, (a1, a2) -> Integer.compare(a1.length, a2.length));

e.g.,

import java.util.Arrays;

public class Sort2DArrays {
    public static void main(String[] args) {
        String[][] terms = { { "java", "php", "ruby", "csharp", "dotnet", "perl" },
                { "google", "apple", "oracle", "microsoft", "sun" },
                { "http", "web", "dns", "net", "protocol", "packet", "ip" },
                { "london", "madrid", "berlin", "ankara", "astana" } };

        Arrays.sort(terms, (a1, a2) -> Integer.compare(a1.length, a2.length));

        for (String[] term : terms) {
            System.out.println(Arrays.toString(term) + ", length: " + term.length);
        }
    }
}