For example, key 1 will have values "A","B","C" but key 2 will have value "D". If I use
例如,键1将具有值“A”,“B”,“C”,但键2将具有值“D”。如果我使用
Map<String, List<String>>
I need to populate the List<String>
even when I have only single String value. What data structure should be used in this case?
我需要填充List
1 个解决方案
#1
1
Map<String,List<String>>
would be the standard way to do it (using a size-1 list when there is only a single item).
Map
You could also have something like Map<String, Object>
(which should work in either Java or presumably C#, to name two), where the value is either List<String>
or String
, but this would be fairly bad practice, as there are readability issue (you don't know what Object
represents right off the bat from seeing the type), casting happens during runtime, which isn't ideal, among other things.
你也可以使用Map
It does however depend what type of queries you plan to run. Map<String,Set<String>>
might be a good idea if you plan of doing existence checks in the List
and it can be large. Set<StringPair>
(where StringPair
is a class with 2 String
members) is another consideration if there are plenty of keys with only 1 mapped value. There are plenty of solutions which would be more appropriate under various circumstances - it basically comes down to looking at the type of queries you want to perform and picking an appropriate structure according to that.
但它确实依赖于您计划运行的查询类型。如果您计划在List中进行存在检查并且它可能很大,那么Map
#1
1
Map<String,List<String>>
would be the standard way to do it (using a size-1 list when there is only a single item).
Map
You could also have something like Map<String, Object>
(which should work in either Java or presumably C#, to name two), where the value is either List<String>
or String
, but this would be fairly bad practice, as there are readability issue (you don't know what Object
represents right off the bat from seeing the type), casting happens during runtime, which isn't ideal, among other things.
你也可以使用Map
It does however depend what type of queries you plan to run. Map<String,Set<String>>
might be a good idea if you plan of doing existence checks in the List
and it can be large. Set<StringPair>
(where StringPair
is a class with 2 String
members) is another consideration if there are plenty of keys with only 1 mapped value. There are plenty of solutions which would be more appropriate under various circumstances - it basically comes down to looking at the type of queries you want to perform and picking an appropriate structure according to that.
但它确实依赖于您计划运行的查询类型。如果您计划在List中进行存在检查并且它可能很大,那么Map