fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. String[][] data = new String[4][];
  13.  
  14. data[0] = new String[4];
  15. data[0][0] = "Columbia";
  16. data[0][1] = "Chile";
  17. data[0][2] = "Asia";
  18. data[0][3] = "US";
  19.  
  20. data[1] = new String[3];
  21. data[1][0] = "B216";
  22. data[1][1] = "B217";
  23. data[1][2] = "A442";
  24. // data[1][3] = "N665";
  25.  
  26. data[2] = new String[4];
  27. data[2][0] = "This";
  28. data[2][1] = "Is";
  29. data[2][2] = "So";
  30. data[2][3] = "Cool";
  31.  
  32. data[3] = new String[3];
  33. data[3][0] = "Holy";
  34. data[3][1] = "Z";
  35. data[3][2] = "AZZZ";
  36.  
  37. List<String[]> list = new ArrayList<>();
  38.  
  39. // Sort the String array and insert it in List
  40. for (String dataArr[] : data) {
  41. String s[] = dataArr.clone(); // create new object of String array
  42. Arrays.sort(s); // Sort newly created String array
  43. list.add(s);
  44. }
  45.  
  46. // Sort the list using custom comparator
  47. Collections.sort(list, new Comparator<String[]>() {
  48.  
  49. @Override
  50. public int compare(String[] o1, String[] o2) {
  51.  
  52. // optional: condition to check for string length equality
  53. if (o1.length == o2.length) {
  54. for (int i = 0; i < o1.length; i++) {
  55. if (o1[i].equals(o2[i])) { // ** IMP **
  56. // allows scanning through entire string array.
  57. continue;
  58. }
  59. // Find the first different strings in both arrays
  60. return o1[i].compareTo(o2[i]);
  61. }
  62. } else if (o1.length < o2.length) {
  63. // allow string arrays with lesser elements to appear first
  64. return -1;
  65. } else if (o1.length > o2.length) {
  66. return 1;
  67. }
  68.  
  69. // When o1.length == o2.length and all strings are equal
  70. return 0; // no difference
  71. }
  72.  
  73. });
  74.  
  75. // Printing the original array and our list
  76. System.out.println(Arrays.deepToString(data));
  77. System.out.println();
  78. for (String s[] : list) {
  79. System.out.println(Arrays.toString(s));
  80. }
  81.  
  82. }
  83. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
[[Columbia, Chile, Asia, US], [B216, B217, A442], [This, Is, So, Cool], [Holy, Z, AZZZ]]

[A442, B216, B217]
[AZZZ, Holy, Z]
[Asia, Chile, Columbia, US]
[Cool, Is, So, This]