Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array alphabetically in java

Tags:

java

In my program, I am reading data from a CSV file which follows the pattern of dance group and then the dancers in the group. I am struggling to sort the dancers names alphabetically.

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

list all dancers method which takes an input of a dance name and then prints out the dance name followed by the dancers inside reading from the CSV file

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;
}
like image 336
Marius Kuzm Avatar asked Jul 28 '26 22:07

Marius Kuzm


1 Answers

In your listAllDancersIn method, use an ArrayList instead of your result += instructions.

Then at end, you can use the default sorter, which will sort alphabetically:

Collections.sort(resultAsList);

ANd if you still want this method to return a sorted string, instead of a sorted list, you can do it this way, using Join method:

return String.join(", ", resultAsList);
like image 139
Bsquare ℬℬ Avatar answered Aug 01 '26 06:08

Bsquare ℬℬ