I have retrieved data from a 2-column CSV file using HashMap. This is for use in a dictionary-style app – one column contains terms and the second contains definitions, which are linked to the terms by the HashMap.
The first thing my app does is print out the list of terms as a list. However, they seem to all come out in a random order.
I’d like them to remain in the same order that they were in in the CSV file (I won’t rely on any alphabetising methods, since I have the occasional non-standard characters and would prefer to alphabetise at the source)
Here’s my code, which extracts the data from the CSV file and prints it to a list:
String next[] = {}; // 'next' is used to iterate through dictionaryFile
final HashMap<String, String> dictionaryMap = new HashMap<String, String>(); // initialise a hash map for the terms
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("dictionaryFile.csv")));
while((next = reader.readNext()) != null) { // for each line of the input file
dictionaryMap.put(next[0], next[1]); // append the data to the dictionaryMap
}
} catch (IOException e) {
e.printStackTrace();
}
String[] terms = new String[dictionaryMap.keySet().size()]; // get the terms from the dictionaryMap values
terms = dictionaryMap.keySet().toArray(terms);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, terms));
ListView lv = getListView();
This causes the app to load, with the terms in place, but they are in a completely obscure order. How do I get them to print in the same order they originally were in?
The problem is that a normal
HashMapdoes not guarantee the order.This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.Try using a
LinkedHashMap, it will maintain the insertion order.From the documentation –
Hash table and linked list implementation of the Map interface, with predictable iteration orderHere is a link to the docs – http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html