3

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;
}
7
  • What is listAllDancersIn? Commented Dec 12, 2018 at 13:38
  • What difficulties are you facing with the sort? What did you try so far? Commented Dec 12, 2018 at 13:39
  • 1
    You could use the Arrays.sort() Commented Dec 12, 2018 at 13:40
  • it would be alot easier if after you split your file into a String Array, you save it into another arrayList and then use the Collections library to sort your items. Commented Dec 12, 2018 at 13:40
  • @Nikolas I have added the method Commented Dec 12, 2018 at 13:41

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thank you very much. This pretty much does the idea that I wanted
0

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

1 Comment

thank you this has sorted all of the dance group names alphabetically, how would i go around sorting data that is returned by (listAllDancersIn(splitByTab[0].trim())) and that method just returns a string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.