java - 在java中按字母顺序对数组进行排序

标签 java

在我的程序中,我正在从 CSV 文件中读取数据,该文件遵循舞蹈组的模式,然后是组中的舞者。我正在努力按字母顺序对舞者的名字进行排序。

public String listAllDancesAndPerformers() {

    // get CSV file for dances Data
    ArrayList<String> dancesData = getCSV("src/csvFiles/danceShowData_dances.csv");

    int lineNumber = 0;
    String result = "";

    //for each line in dances csv file
    for (String line : dancesData) {

        //split into two sections - [0] is name of dance & [1] is dancers
        String[] splitByTab = line.split("\t");


         //take the dancers [1] of splitByTab and split it by commas
         // this makes that seperatedNames[1], [2] etc are all the dancers
         //and i am supposed to sort the seperated names to print out alphabetticaly
        String[] separatedNames = splitByComma(splitByTab[1]);


        lineNumber++;
        result += lineNumber + ": ";
        result += (splitByTab[0].trim()) + "\n";



        result += (listAllDancersIn(splitByTab[0].trim())) + "\n";


    }

    return result;
}

列出所有舞者方法,该方法输入舞蹈名称,然后打印出舞蹈名称,后面是从 CSV 文件中读取的舞者

public String listAllDancersIn(String dance) {
    // get CSV file for dances Data
    ArrayList<String> dancesData = getCSV("src/csvFiles/danceShowData_dances.csv");

    String result = "";

    // for each line in dances csv file
    for (String line : dancesData) {

        // split into two sections - [0] is name of dance & [1] is dancers
        String[] splitByTab = line.split("\t");

        splitByTab[0] = splitByTab[0].trim();

        // if name of dance matches given dance name
        if (splitByTab[0].equals(dance)) {

            // split names of dancers into individual strings
            String[] separatedNames = splitByComma(splitByTab[1]);

            // iterate through names
            for (int i = 0; i < separatedNames.length; i++) {
                // append result with output of getDanceGroupMembers (and trim input)
                result += ", " + getDanceGroupMembers(separatedNames[i].trim());
            }
        }
    }

    // remove leading comma and space
    result = result.substring(2);

    return result;
}

最佳答案

在您的 listAllDancersIn 方法中,使用 ArrayList 代替您的 result += 指令。

最后,您可以使用默认的 sorter ,它将按字母顺序排序:

Collections.sort(resultAsList);

如果您仍然希望此方法返回排序后的字符串,而不是排序后的列表,您可以使用 Join method 以这种方式实现:

return String.join(", ", resultAsList);

关于java - 在java中按字母顺序对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53744319/

相关文章:

java - 使用相同的动画为多个 View 设置动画

Java 编译器问题 : cannot find symbol

java - 需要有关在网络上显示(和/或转换)pdf 文件的建议

java - 使用链表实现二叉堆

java - ImageView setScaleType 不工作

java - 从 List1 中删除值也会从 List2 中删除值吗?

java - 没有带有自定义文本的新行?

java - 关于 XML 模式的 Json 到 XML 到 Json

java - 这是什么文档格式?

java - 在输入流中等待时执行某些操作