What is the best way to convert a Map<key,value>
to a List<value>
? Just iterate over all values and insert them in a list or am I overlooking something?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
If you want to ensure the values in the resultant
List<Value>
are in the key-ordering of the inputMap<Key, Value>
, you need to "go via"SortedMap
somehow.Either start with a concrete
SortedMap
implementation (Such asTreeMap
) or insert your inputMap
into aSortedMap
before converting that toList
. e.g.:Otherwise you'll get whatever native ordering the
Map
implementation provides, which can often be something other than the natural key ordering (TryHashtable
orConcurrentHashMap
, for variety).The issue here is that
Map
has two values (a key and value), while aList
only has one value (an element).Therefore, the best that can be done is to either get a
List
of the keys or the values. (Unless we make a wrapper to hold on to the key/value pair).Say we have a
Map
:The keys as a
List
can be obtained by creating a newArrayList
from aSet
returned by theMap.keySet
method:While the values as a
List
can be obtained creating a newArrayList
from aCollection
returned by theMap.values
method:The result of getting the
List
of keys:The result of getting the
List
of values:we can have both key and value pair in list.Also can get key and value using Map.Entry by iterating over list.