如何按java中的元素数量对2D String数组进行排序

时间:2016-10-08 23:56:12

标签: java arrays string sorting multidimensional-array

我知道这可能是一个简单的问题,但我无法想出适当的算法。我有一个2d的字符串数组,我想按元素的数量排序:假设数组如下:

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



      }
  }

如何以这种方式按元素数量排序数组(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]

另外,对我来说很有意思,当每个组中元素的数量相等时会发生什么,例如“google”和“london”组具有相同数量的元素。谢谢你的帮助!

2 个答案:

答案 0 :(得分:3)

使用java.util.Arrays.sort(...)the Arrays class API link)。其中一个方法重载采用带有Comparator参数的数组参数,在比较器的compare(...)方法中,比较子数组的 length

如,

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

如,

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

答案 1 :(得分:0)

冒泡排序

import java.util.Arrays;

public class BubbleSort {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
     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" } };
     // The cycle time will put the biggest that number in the I That is the highest one .
     //That is why the algorithm called Bubble Sort, because every time like bubbles rise.
     for(int i =terms.length-1;i>=0;--i)
     {
         //The cycle time will traverse 0--(i-1),And when comparing the size of the adjacent two.
         //they will be big like bubbles rise up, and is actually exchange two object
         for(int j=0;j<=i-1;j++)
         {
             if (terms[j].length>terms[j+1].length) {
                 String[] term= terms[j];
                 terms[j] = terms[j+1];
                 terms[j+1]= term;
            }

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

}

}