I have data like below:
Key value
----- ------
car toyota
car bmw
car honda
fruit apple
fruit banana
computer acer
computer asus
computer ibm
...
(Each row of above data is an object with fields "key" and "value", all in one List List<DataObject>
)
I would like to construct the data to a Map<String, List<String>>
like following:
"car" : ["toyota", "bmw", "honda"]
"fruit" : ["apple","banana"]
"computer" : ["acer","asus","ibm"]
How to achieve above Map
structure from the data objects?
******Besides******
I am more interested in using pure JDK provided classes or interfaces to achieve the result instead of using external library. Any help?
The below snippet should help you.
Something like this perhaps?
Pseudocode:
Alternatively, use Guava
ListMultiMap
.I would use the guavas
Multimap
implementation. But it is easy doable with the standard JDK aswell.Example standard JDK:
Example guava:
Output (both implementations):
Iterate over the objects. For each object, get its corresponding list from the map. If null, create a new list and put it in the map. Then add the value to the list.
Or Use Guava's ListMultimap, which will do this for you.