This is not a complete code nor it was tested. It may or may not work but it will guide you anyways.
// Java 8
Node n;
Edge e;
String[] splittedLine;
String[] splittedEdge;
HashMap<String, Node> stationNumberToNode = new HashMap<>();
// if the file is not too large, you can read the file at once
List<String> lines = Files.readAllLines(new File("path/to/file.txt").getPath());
for(String line : lines){
splittedLine = line.split(" ");
if((n = stationNumberToNode.get(splittedLine[0]) == null){
n = new Node(splittedLine[0]); // assuming your Node has a constructor that takes the station id
stationNumberToNode.put(stationNumberToNode[0], n);
}
for(int i = 1; i < splittedLine.lenght; ++i){
splittedEdge = splittedLine[i].split(",");
e = new Edge(splittedEdge[0], splittedEdge[1]); // assuming your Edgehas a constructor that takes the destination station and the cost
n.addEdge(e);
}
}
Explanation
Node n;
Edge e;
String[] splittedLine;
String[] splittedEdge;
HashMap<String, Node> stationNumberToNode = new HashMap<>();
Ideally you should always declare variables outside loops, so you avoid allocating a new memory on every iteration. Thus, we declare our 5 variables before entering the loop. The HashMap
is used here to cover the case that your input is not always grouped and you avoid having to perform a list search everytime.
List<String> lines = Files.readAllLines(new File("path/to/file.txt").getPath());
Read all the lines on the file at once. Alternatively, as requested on the question, you can read the file using Scanner
like on this anwer. You have to change the way you iterate over the lines, though.
splittedLine = line.split(" ");
Splits the line on the " ", since your input file is well formated.
if((n = stationNumberToNode.get(splittedLine[0]) == null){
n = new Node(splittedLine[0]); // assuming your Node has a constructor that takes the station id
stationNumberToNode.put(stationNumberToNode[0], n);
}
Checks if the current node is already on the HashMap
. If yes, it will be stored in the variable n
. Else, it will create a Node
with the current id and add it to our HashMap
.
for(int i = 1; i < splittedLine.lenght; ++i){
splittedEdge = splittedLine[i].split(",");
e = new Edge(splittedEdge[0], splittedEdge[1]); // assuming your Edgehas a constructor that takes the destination station and the cost
n.addEdge(e);
}
Since everything in the input file is the destination station and its cost (id,cost), we iterate on the splittedLine
from index 1 onwards.
For every edge data, we split based on "," (from your input file), whereas splittedEdge[0]
will be the destination id and splittedEdge[1]
will be the cost to that destination. We create an Edge
with that information and add that Edge
to the Node
object.