I have a setup where each of my "People" map to a specific "Room".
However, multiple people can map to the same room.
If an existing person is seen, their room should be updated to the new value.
So this is the traditional use case for Map<Person, Room>.put(Person, Room)
However, the lookup is always going to be "Which people are in this room?"
Set<People> get(Room q){}
I can obviously craft my own datastructure or simply iterate over the key-value pairs; but does one of the Java collections libraries have a good structure to support both the referential integrity and lookup I need?
To answer your specific question, no, you can't do it all with one data structure. I would solve it with
Map<Person,Room> personRoom;
SetMultimap<Room,Person> roomPeople;
void addPersonToRoom(Person p,Room r){
Room currentRoom = personRoom.get(p);
if (currentRoom != null)
roomPeople.remove(currentRoom, p);
personRoom.put(p,r);
roomPeople.put(r,p);
}
Set<Person> getPeopleInRoom(Room r){
return roomPeople.get(r);
}
Room getRoomForPerson(Person p){
return personRoom.get(p);
}