I hold the followi开发者_开发技巧ng map
Map<Integer, List<String>>
when I add a new string to a certain int I just add it to the list of that int value in my map.
Now, I also need to remove it from the last list it was located in. I will elaborate for a second : It is not the same instance of the string. I get an int and a String, I need to add it and remove it from the former List in the map that held the same string value.This means that I need to hold another map of String to Integer ?
Do I need to maintain two collections? thanks.It's kind of like a BiMap, but since your relationship is assymetrical (one int
refers to a List
of String
s whereas a String
can only refer to one int
), it's not going to be a perfect mtach.
It sounds to me as though you want two maps, the first being your Map<Integer, List<String>>
and the second being a Map<String, Integer>
. You'd want to encapsulate this in class, of course. Adding a new string is then:
- If there's an entry for the
String
inMap<String, Integer>
,- Get the
Integer
from that list. - Use it to look up the
List
from yourMap<Integer, List<String>>
and remove theString
from it.
- Get the
- Add the
String
to the relevantList
in yourMap<Integer, List<String>>
- Add an entry mapping the
String
to theInteger
in theMap<String, Integer>
.
You could try using Guava's BiMap.
精彩评论