HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaModerate

Sorting numbers using Java Collections.sort()

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortingnumbersjavausingcollectionssort

Problem

Input is a file containing numbers in this format:

1.2 3 5.1 2 7 4 6
5 2 9.22 1 0.0 4 3


I am doing the sorting in the simplest way, using Collections.sort method. The running code is as follows:

`import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class SortedNumbers {

public static Double integerFromString(String str) {
return Double.valueOf(str.substring(0, str.length()));
}

public static void main(String[] args) throws FileNotFoundException {
String fileName = "";

//scanner to read the file
Scanner fileInput = null;

List temps = new LinkedList();

//first check if there is an input parameter
if(args.length > 0) {
fileName = args[0];
}

else {
System.out.println("No file specified");
System.exit(1);
}

//connect to the file
FileReader file = new FileReader (fileName);
fileInput = new Scanner(file);

//start reading from the file, store all the lines in the list
while(fileInput.hasNextLine()) {
String num = fileInput.nextLine();
temps.add(num);
}

//close the scanner
fileInput.close();

//convert the list into array of strings
String[] str = temps.toArray(new String[0]);

/**
* for each string in str array, split it using space as the delimiter and store the splitted strings in an array,
* for each string value in the array, convert it into Double and store it in a collection
* Sort the collection, convert it into String
*/
for(int i = 0; i num = new LinkedList();
String[] arr = str[i].split("\\s");
for(int j = 0; j

I am concerned about the performance, splitting the string and storing it in array, parsing each string fr

Solution

There are a few improvements I can see, but not really related to performance (though it may run a bit faster anyway).

If the files are small (less than 10Megabytes or so), then the relative performance of different approaches are slight (obviously, you can bork your code, but the IO part will remain about the same). So, it comes down to readability.

For readability, I would recommend using the 'cool' toys in Java7. Consider the following:

List lines = Files.readAllLines(Paths.get(args[0]));
for (String line : lines) {
    String[] parts = line.split("\\s+");
    double[] values = new double[parts.length];
    for (int i = 0; i  0) {
            sb.append(", ");
        }
        sb.append(values[i]);
    }
    System.out.println(sb.toString());       
}


Note the key elements here:

  • use Files and Paths classes



  • use StringBuilder for the string concatenation



  • use String.split, not a scanner....



  • use primitive data structures (arrays of double, not Double)



  • that means using Arrays.sort, not Collections.sort



Other things to consider.....

  • a method called integerFromString ... that returns a double is ... confusing.



  • using List.toString() and the stripping off the [ and ] is backward.

Code Snippets

List<String> lines = Files.readAllLines(Paths.get(args[0]));
for (String line : lines) {
    String[] parts = line.split("\\s+");
    double[] values = new double[parts.length];
    for (int i = 0; i < parts.length; i++) {
        values[i] = Double.parseDouble(values[i]);
    }
    Arrays.sort(values);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < values.length; i++) {
        if (i > 0) {
            sb.append(", ");
        }
        sb.append(values[i]);
    }
    System.out.println(sb.toString());       
}

Context

StackExchange Code Review Q#52158, answer score: 14

Revisions (0)

No revisions yet.