如何操作类似于SQL中的ORDER BY子句的数组?

时间:2010-02-17 09:50:43

标签: java sql arrays sql-order-by processing

我的数据已被放入一个数组中,但遗憾的是不是我希望它的顺序......

String[][] databaseToArray = {
  //{"Name", "Channel", "Description", "Amount", "isReady"},
    {"John", "Nick",    "likes",       "2",      "yes"    },
    {"Drew", "MTV",     "dislikes",    "4",      "no"     },
    {"Fred", "CNN",     "okay",        "3",      "no"     },
    {"Beth", "Fox",     "valid",       "1",      "yes"    }
};

我如何操纵这个数组,以便当我遍历它时,顺序是数量,类似于SELECT * FROM "databaseToArray" ORDER BY "Amount"又名

String[][] reorganizedArray = {
  //{"Name", "Channel", "Description", "Amount", "isReady"},
    {"Beth", "Fox",     "valid",       "1",      "yes"    },
    {"John", "Nick",    "likes",       "2",      "yes"    },
    {"Fred", "CNN",     "okay",        "3",      "no"     },
    {"Drew", "MTV",     "dislikes",    "4",      "no"     }
};

2 个答案:

答案 0 :(得分:2)

您需要将Comparator传递给Arrays.sort方法。我在5年内没有完成Java,但它应该很容易实现。也许有人可以清理这个我即将写的例子,因为我很确定我会出错。

String[][] databaseToArray = {
  //{"Name", "Channel", "Description", "Amount", "isReady"},
    {"John", "Nick",    "likes",       "2",      "yes"    },
    {"Drew", "MTV",     "dislikes",    "4",      "no"     },
    {"Fred", "CNN",     "okay",        "3",      "no"     },
    {"Beth", "Fox",     "valid",       "1",      "yes"    }
};

Arrays.sort(databaseToArray, new Comparator<String[]>() {
    public int compare(String[] a, String[] b) {
        return a[3].compareTo(b[3]);
    }
});

答案 1 :(得分:-1)

我在处理网站上找到了排序方法,但这只适用于One-Dimensional Arrays ......

http://processing.org/reference/sort_.html

   float[] a = { 3, 5, 2, 4, 1 };
   a = sort(a);
   println(a);
// Prints 1, 2, 3, 4, 5