I have an input file that looks like this
@id1 1.2 3.4
@id2 6.8 8.1
@id3 1.5 9.4
@id4 5.9 2.7
I would like to store the numbers only in a 2D array, and forget about the 1st column that contains the @id. I also want to use streams only for that operation.
So far I made 2 methods :
First method read the input file and store each lines in a List, as an array of string :
private List<String[]> savefromfile(String filePath) throws IOException {
List<String[]> rowsOfFile = new LinkedList<String[]>();
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
lines.forEach(line -> {
String rows[] = line.trim().split("\\s+");
rowsOfFile.add(rows);
});
lines.close();
}
return rowsOfFile;
The second method take as an input the List, and return a 2D Array that contains only the columns numbers :
private double[][] storeAllID(List<String[]> rowsOfFile) {
int numberOfID = rowsOfFile.size();
double[][] allID = new double[numberOfID][2];
int i = 0;
for (String[] line : rowsOfFile) {
double id[] = new double[2];
id[0] = Double.parseDouble(line[1]);
id[1] = Double.parseDouble(line[2]);
allID[i++] = id;
}
return allID;
}
Is there a way to make this code more efficient ? I want only one, short method that read the input file and return a 2D array containing numbers only. I don't think it's necessary to write 20 lines of code to do this.