简体   繁体   中英

Sorting an array of strings alphabetically

I have written the following working code. I believe it could be made better or more efficient but I'm not too sure how to go on about it.

The main thing that I'm unhappy with is the three replaces.

ArrayList<String> test = new ArrayList<String>(); 
for (int i = 0; i < user.getTasks().size(); i++) {
    test.add(user.getTasks.get(i).getTask().toString());
}
Collections.sort(test);
System.out.println(test.toString().replace(",", " |").replace("[", "").replace("]", ""));

The output is something like follows: Tast1 | Task2 | Task3 and it is good.

Please don't hesitate to ask any questions, I'm super responsive.

Since you are using Java 7 and streams are not available, you can:

  1. use the simpler for syntax (assuming user.getTasks() returns a list of Task objects - replace Task with your class if not)
  2. loop through the strings, concatenating them with the separator

ArrayList<String> test = new ArrayList<String>(); 
for (Task task : user.getTasks()) {
    test.add(task.getTask().toString());
}
Collections.sort(test);

// make a string of the values with a pipe separator
StringBuilder valuesToPrint = new StringBuilder();
for (int index = 0; index < test.size(); index++) {
    if (index > 0) {
        valuesToPrint.append(" | ");
    }
    valuesToPrint.append(test);
}

System.out.println(valuesToPrint.toString());

Java 8+ you could simplify it as:

List<String> test = new ArrayList<String>(); 
String result = user.getTasks().stream()
                               .map(t -> t.getTask().toString())
                               .sorted()
                               .collect(Collectors.joining("|"));
System.out.println(result);

Which will create a Stream of the String 's in the list, sort them, and then join them into a String with | in between each item

Or if you need to do other operations on the sorted list, you could sort it and then do the stream part after:

Collections.sort(test);
String result = test.stream().collect(Collectors.joining("|"));

As pointed out, Java 8 Stream API provides a lot of utilities to perform those kind of tasks, but if you want to keep your solution using loops and you want to avoid the three replaces, instead of calling toString() on the list and then cleaning it up, you should loop the items on the list while building a String

String result = "";
for (String item : test) {
    result += item + " | ";
}
System.out.println(result.substring(0, result.length() - 3);

Note that you print the result cutting out the last three characters to avoid printing Tast1 | Task2 | Task3 |

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