从数据库表中检索列的行并对行的每个单词进行排序

时间:2016-02-11 11:18:30

标签: java jdbc

应用排序后,我按照排序方式得到一些句子,而在其他句子中,所有单词都被排序,但除了第一个单词。 例如,Amako; Jun(Shiojiri,JP),Umetsu; Kazushige(Chino,JP),Tanaya;英雄(Su访,JP)

青木; Shigenori(川崎,JP),加藤; Masayuki(川崎,JP)

De Dobbelaere;彼得(加利福尼亚州圣地亚哥),Pinguet;蒂埃里(华盛顿州阿灵顿),彼得森;马克(加利福尼亚州圣地亚哥),哈里森;马克(埃斯孔迪多,加州),迪金森; Alexander G.(Laguna Beach,CA),Gunn,III; Lawrence C.(Encinitas,CA)

输出是 - Hideo(Suwa,JP)Jun(Shiojiri,JP),Umetsu Kazushige(Chino,JP),Tanaya Amako

Masayuki(Kawasaki,JP)Shigenori(Kawasaki,JP),Kato Aoki

Alexander G.(Laguna Beach,CA),Gunn,III Lawrence C.(Encinitas,CA)Mark(Escondido,CA),Dickinson Mark(San Diego,CA),Harrison Peter(San Diego,CA),Pinguet Thierry(华盛顿州阿灵顿),Peterson De Dobbelaere

代码示例:

ResultSet rs = stmt.executeQuery(sql);
List<String> results = new ArrayList<String>();

while (rs.next()) {
    results.add(rs.getString(1));
}
for (int i = 1; i < results.size(); i++) {
    ArrayList<String> lines = new ArrayList<String>(results);
    ArrayList<String> newLines = new ArrayList<String>(results);

    for (String line : lines) {
        line = line.substring(0, line.length() - 2).trim();
        String[] words = line.split(";");
        Arrays.sort(words);
        StringBuilder sb = new StringBuilder(line.length());
        for (String word : words) {
            if (word.isEmpty())
                continue;
            if (sb.length() > 0) {
                sb.append("    ");
            }
            sb.append(word);
        }
        String newLine = sb.toString();
        newLines.add(newLine);
    }

    System.out.println("sorted lines:");
    for (String line : newLines) {
        System.out.println(line);
    }
}   

2 个答案:

答案 0 :(得分:1)

您可以在SQL中按名称检索它。

SELECT firstName, lastName
FROM myTable
ORDER BY lastName ASC; 

(或DESC,如果你想要Z到A)

答案 1 :(得分:0)

  1. 拆分每一行String@split("; ")

  2. 使用Arrays#sort(-)对其进行排序。

  3. 例如:

    ArrayList<String> lines = new ArrayList<String>();
    
    //for (int i = 0; i < results.size(); i++){
    
    String in = "Amako; Jun (Shiojiri, JP), Umetsu; Kazushige (Chino, JP)," 
                 +"Tanaya; Hideo (Suwa, JP)  ,";
    //in = (String)results.get(i);
    in = in.substring(0, in.length()-2).trim();
    
    String str[] = in.split("; ");//1
    
    Arrays.sort(str);//2
    
    StringBuffer sb = new StringBuffer();
    for(String s:str)
        {
            System.out.println(s);
            sb.append(s);
            sb.append("; ");
        }
    
    
        System.out.println(sb.toString().substring(0, sb.toString().length()-2));
    
        lines.add(sb.toString().substring(0, sb.toString().length()-2));
    //}
    

    输出:

    Amako; Hideo (Suwa, JP) ; Jun (Shiojiri, JP), Umetsu; Kazushige (Chino, JP), Tanaya
    

    对剩下的行做同样的事情..