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<String> temps = new LinkedList<String>();
//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 < str.length; i++){
List<Double> num = new LinkedList<Double>();
String[] arr = str[i].split("\\s");
for(int j = 0; j < arr.length; j++){
Double currentNumber = integerFromString(arr[j]);
num.add(currentNumber);
}
Collections.sort(num);
String sortedNumbers = num.toString();
int indexOfOpenBracket = sortedNumbers.indexOf("[");
int indexOfLastBracket = sortedNumbers.lastIndexOf("]");
System.out.println(sortedNumbers.substring(indexOfOpenBracket+1, indexOfLastBracket));
}
}
}
I am concerned about the performance, splitting the string and storing it in array, parsing each string from array into double and then adding in the list. It seems like there could be an efficient way.
Are there any redundant steps in the code which I can avoid?