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?
Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap.
Now need is to convert the String to a Map object so that each student roll number becomes the key of the HashMap, and the name becomes the value of the HashMap object. In order to convert strings to HashMap, the process is divided into two parts: The input string is converted to an array of strings as output.
Map<String, List<String>> myMaps = new HashMap<String, List<String>>();
for (DataObject item : myList) {
if (!myMaps.containsKey(item.getKey())) {
myMaps.put(item.getKey(), new ArrayList<String>());
}
myMaps.get(item.getKey()).add(item.getValue());
}
I would use the guavas Multimap
implementation. But it is easy doable with the standard JDK aswell.
public static void main(String[] args) {
Scanner s = new Scanner(
"car toyota\n" +
"car bmw\n" +
"car honda\n" +
"fruit apple\n" +
"fruit banana\n" +
"computer acer\n" +
"computer asus\n" +
"computer ibm");
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
while (s.hasNext()) {
String key = s.next();
if (!map.containsKey(key))
map.put(key, new LinkedList<String>());
map.get(key).add(s.next());
}
System.out.println(map);
}
public static void main(String[] args) {
Scanner s = new Scanner(
"car toyota\n" +
"car bmw\n" +
"car honda\n" +
"fruit apple\n" +
"fruit banana\n" +
"computer acer\n" +
"computer asus\n" +
"computer ibm");
Multimap<String, String> map = LinkedListMultimap.create();
while (s.hasNext())
map.put(s.next(), s.next());
System.out.println(map);
}
Output (both implementations):
{car=[toyota, bmw, honda], fruit=[apple, banana], computer=[acer, asus, ibm]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With