Basically, I got a file containing details about people, each person separated by a new line, e.g
“
name Marioka address 97 Garderners Road birthday 12-11-1982 \n
name Ada Lovelace gender woman\n
name James address 65 Watcher Avenue
” and so on..
And, I would like to parse them to [Keyword : Value] pair array, such as
{[Name, Marioka], [Address, 97 Gardeners Road], [Birthday, 12-11-1982]},
{[Name, Ada Lovelace], [Gender, Woman]}, and so on....
and so on. The keywords will be a set of defined words, in above case: name, address, birthday, gender, etc…
What is the best way to do this?
This is how I did it, it works but was wondering whether there are better solutions.
private Map<String, String> readRecord(String record) {
Map<String, String> attributeValuePairs = new HashMap<String, String>();
Scanner scanner = new Scanner(record);
String attribute = "", value = "";
/*
* 1. Scan each word.
* 2. Find an attribute keyword and store it at "attribute".
* 3. Following words will be stored as "value" until the next keyword is found.
* 4. Return value-attribute pairs as HashMap
*/
while(scanner.hasNext()) {
String word = scanner.next();
if (this.isAttribute(word)) {
if (value.trim() != "") {
attributeValuePairs.put(attribute.trim(), value.trim());
value = "";
}
attribute = word;
} else {
value += word + " ";
}
}
if (value.trim() != "") attributeValuePairs.put(attribute, value);
scanner.close();
return attributeValuePairs;
}
private boolean isAttribute(String word) {
String[] attributes = {"name", "patientId",
"birthday", "phone", "email", "medicalHistory", "address"};
for (String attribute: attributes) {
if (word.equalsIgnoreCase(attribute)) return true;
}
return false;
}
To extract values from a string, use regular expressions. I expect you to know how to read each line from a file and how to build up an array with the results.
Still this is not a good solution, since it doesn’t work if any of the keywords are included in the name or address… But that’s what you asked for…