简体   繁体   中英

Sorting an array alphabetically in 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;
}

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

I think you should split your code:

  1. Read CSV file and build correct data structure;
  2. Print data structure to console or String .

public static Map<String, Set<String>> listAllDancesAndPerformers() {
    final Pattern pattern = Pattern.compile("(?<group>\\w+)\\t+(?<dancers>.+)");
    final Pattern comma = Pattern.compile("\\s*,\\s*");
    Map<String, Set<String>> groups = new TreeMap<>();

    for (String line : getCSV("src/csvFiles/danceShowData_dances.csv")) {
        Matcher matcher = pattern.matcher(line);

        if (matcher.matches())
            groups.put(matcher.group("group"), new TreeSet<>(Arrays.asList(comma.split(matcher.group("dancers")))));
    }

    return groups;
}

If danceShowData_dances.csv file content is:

beginners   anna,maria,olga
mature      bob,marvin,peter

Then result Map will contain:

"beginners" : ["anna", "maria", "olga"]
"mature" : ["bob", "marvin", "peter"]

And finally you can create method that convert given Map into String with required format:

public static String printToString(Map<String, Set<String>> groups) {
    int count = 1;
    StringBuilder buf = new StringBuilder();

    for (Map.Entry<String, Set<String>> entry : groups.entrySet()) {
        if (buf.length() > 0)
            buf.append('\n');

        buf.append(count++).append(':');
        buf.append(entry.getKey());

        if (!entry.getValue().isEmpty())
            buf.append('\n').append(String.join(", ", entry.getValue()));
    }

    return buf.toString();
}

Output:

1:beginners
anna, maria, olga
2:mature
bob, marvin, peter

Marius, see whether below code works as you intended.

import java.util.ArrayList;
import java.util.Collections;

public class SortDancers {

    public static void main(String[] args) {

        System.out.println(new SortDancers().listAllDancesAndPerformers());
    }

    public String listAllDancesAndPerformers() {

        ArrayList<String> dancesData = new ArrayList<String>();
        dancesData.add("Dance1 \t Kelly, Andrew, Nathan");
        dancesData.add("Dance2 \t John, Sally, Kevin, Abby");
        dancesData.add("Dance3 \t Laura, Benny, Jane");
        // I assume you get this kind of data from getCSV()

        int lineNumber = 0;
        String result = "";

        for (String line : dancesData) {

            String[] splitByTab = line.split("\t");

            String[] separatedNames = splitByTab[1].split(",");

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

            ArrayList<String> separatedNamesList = new ArrayList<String>();
            for (int i = 0; i < separatedNames.length; i++) {
                separatedNamesList.add(separatedNames[i].trim());
            }

            Collections.sort(separatedNamesList);
            result += String.join(", ", separatedNamesList);
            result += "\n";
        }

        return result;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM