I’m having trouble deciding which java collection would fit my scenario best. Currently, I’m reading in a record that gives me an ‘account number’ and a ‘customer name’ values.
Based on these values, I need to search through another file based upon the account number and customer name given from the first file. The problem is that account number is not unique in the second file, so I need to search using both account number and customer name.
Instead of opening, reading, searching, closing the second file for every record I read from the first file, I’d like to read the entire file into a collection and use the Collections binary search to locate the associated record in the second file.
Is there a certain type of collection that would fit this purpose best (if any at all)?
Assuming you have sufficient memory, I would probably use a
HashMap<AccountIdentifier, CustomerRecord>.Where
CustomerRecordis an object that contains the record you where looking for.And then create a key class:
So then you’d have to preload your second file in memory by reading each record and creating an instance of
CustomerRecordwith the data it contains, and also aAccountIdentifierto put in yourMap:theMap.put(accountIdentifier, customerRecord);When comes the time to search, and you’ve got an accountNumber and customerName from the first file, then do:
Final comment, if your file is too big to fit in memory, then you should consider using a cache library like ehcache.