user4188409
user4188409

Reputation: 77

Java - Arraylist / Hash map Questiоn

I want to create a hashmap that stores the keywords from a title of a paticular activity object which is currently stored in an arraylist. So for example i have the following activities stored in the array list:

Football game - 1st activity object in arraylist -- So here the keyword football will be linked to the 1st activity object in the arraylist and the word game will be linked to the 1st activity object in the arraylist.

Baseball game - 2nd activity object in the arraylist -- So here the keyword baseball will be linked to the 1st activity object in the arraylist and the word game will now be linked to the 2nd activity object and in the arraylist.

Dinner - 3rd activity object in the arraylist

When the user does a search with the keyword "game", i want the hashmap to link 1 and 2 in the arraylist because they both have the word game. Im not sure if im doing this right below. Is this the way to do it?

private ArrayList activities = new ArrayList();

HashMap<ArrayList<Activity>, String> map = new HashMap<>();

map.put(new ArrayList<Activity>(),keyword );


There will be a loop here to add keywords from a tokenized string into activities. 

map.get(activities(i)).add(keyword);

Upvotes: 1

Views: 173

Answers (2)

Karo
Karo

Reputation: 273

You can't have multiple value for keyword like "game" because it's function from String to Number. I think you can do this. You have array of activities and a Map from String to a List that save the activity number of that String. for your example the map will have the following values:

  • "Game" -> [1,2]
  • "Football" -> [1]
  • "Baseball" -> [2]
  • "Dinner" -> [3]

and when you have to add new activity you should update your map for example adding "Baseball Class" will change Baseball list from [2] to [2,4] and will create new "Class" that have value [4]

  • "Game" -> [1,2]
  • "Football" -> [1]
  • "Baseball" -> [2,4]
  • "Dinner" -> [3]
  • "Class" -> [4]

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201537

Your Key and Value types appear to be reversed, the Map Javadoc begins,

Interface Map<K,V>

Type Parameters:
   K - the type of keys maintained by this map
   V - the type of mapped values

And, you'll need more then one ArrayList reference! Assuming you have a String key and a Activity act you would first check Map.containsKey(Object) has the key if it does use that List otherwise construct a new one and add it to the map.

String key;
Activity act;
Map<String, List<Activity>> map = new HashMap<>();
List<Activity> list = null;
if (map.containsKey(key)) {
  list = map.get(key);
} else {
  list = new ArrayList<>();
  map.put(key, list);
}
list.add(act);

Upvotes: 1

Related Questions