简体   繁体   English

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

[英]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. 在我的程序中,我正在从CSV文件中读取数据,该文件遵循舞蹈组的模式,然后是组中的舞者。 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 列出所有舞者的方法,其中输入舞蹈名称,然后打印出舞蹈名称,然后是从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;
}

In your listAllDancersIn method, use an ArrayList instead of your result += instructions. listAllDancersIn方法中,使用ArrayList而不是result +=指令。

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 : 如果您仍然希望此方法返回已排序的字符串而不是排序列表,则可以使用Join方法以这种方式执行此操作:

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

I think you should split your code: 我认为你应该拆分你的代码:

  1. Read CSV file and build correct data structure; 读取CSV文件并构建正确的数据结构;
  2. Print data structure to console or String . 将数据结构打印到控制台或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: 如果danceShowData_dances.csv文件内容是:

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

Then result Map will contain: 然后结果Map将包含:

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

And finally you can create method that convert given Map into String with required format: 最后,您可以创建将给定Map转换为具有所需格式的String方法:

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. Marius,看看下面的代码是否按预期工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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