Last, but not least, the data model can be created on the fly and held in memory. A database can be created from an array of preferences, which will hold user ratings for a set of items.
We can proceed as follows. First, we create a FastByIdMap hash map of preference arrays, PreferenceArray, which stores an array of preferences:
FastByIDMap <PreferenceArray> preferences = new FastByIDMap
<PreferenceArray> ();
Next, we can create a new preference array for a user that will hold their ratings. The array must be initialized with a size parameter that reserves that many slots in the memory:
PreferenceArray prefsForUser1 = new GenericUserPreferenceArray (10);
Next, we set the user ID for the current preference at the position 0. This will actually set the user ID for all preferences:
prefsForUser1.setUserID (0, 1L);
Set an itemID for the current preference at the position 0, as follows:
prefsForUser1.setItemID (0, 101L);
Set the preference value for the preference at 0, as follows:
prefsForUser1.setValue (0, 3.0f);
Continue for other item ratings, as follows:
prefsForUser1.setItemID (1, 102L); prefsForUser1.setValue (1, 4.5F);
Finally, add the user preferences to the hash map:
preferences.put (1L, prefsForUser1); // use userID as the key
The preference hash map can now be used to initialize GenericDataModel:
DataModel dataModel = new GenericDataModel(preferences);
This code demonstrates how to add two preferences for a single user; in a practical application, you'll want to add multiple preferences for multiple users.