I found a solution for a while now and I decided to post it, in case anyone needs it
in this solution it doesn't matter the order of the fields and it also accept optional fields
I have an enum with the fields I can get from the file:
public enum Fields {
FIRST_NAME,
AGE,
EMAIL
}
I have an ordinary class with a constructor and setters for the fields, in this class I also have an array to keep any columns
public Map<String, String> otherCol = new HashMap<String, String>();
in the class that handles the file I have an map to hold the columns:
Map<String, Fields> columnsOrderedMap = new HashMap<String, Fields>();
in the class's constructor I pupulate the columns map one by one with all the possible fields it can get:
Map<String, Fields> columns = new HashMap<String, Fields>();
columns.put("First Name", Fields.FIRST_NAME);
columns.put("Age", Fields.AGE);
columns.put("Email", Fields.EMAIL);
then I read the file line by line
int nrOfTokens = tokens.length;
if (lineNr == 1) {
fields = tokens;
nrOfFields = nrOfTokens;
for (int i = nrOfFields - 1; i >= 0; i--) {
if(columns.containsKey(tokens[i]))
columnsOrderedMap.put(tokens[i], columns.get(tokens[i]));
else
columnsOrderedMap.put(tokens[i], ContactsFields.OTHER);
}
and for each value in map:
for(Map.Entry<String, Fields> entry : columnsOrderedMap.entrySet()) {
int index = searchPosition(fields, entry.getKey());
switch(entry.getValue()) {
case FIRST_NAME:
contactsTemplate.setFirstName(tokens[index]);
break;
//...
function to get the right possition of each field in file
public int searchPosition(String[] argsList, String toSearch) {
int position = 0;
int count = -1;
for(String s: argsList) {
count++;
if(s.equals(toSearch)) {
position = count;
break;
}
}
return position;
}
I hope it is helpful for someone, and i apologize because i don't know to explain very well:(