Printing Values From a HashMap Java
Printing Values From a HashMap Java
I have a Java program that I am currently making, and am stuck with printing out the keys and the values associated with each key of my hashMap.
This is the HashMap that I have declared currently:
HashMap<String, ArrayList<String>> mp = new HashMap<>();
Basically assuming that I have the following code written out
mp.put(key1, list.add(value1));
mp.put(key1, list.add(value2));
mp.put(key1, list.add(value3));
mp.put(key2, list.add(value5));
mp.put(key2, list.add(value4));
mp.put(key3, list.add(value6));
I want to print the map out like this:
Is there any way I can get that done? Thanks for all the help I can get. Please let me know if any more clarification is needed.
mp.computeIfAbsent(key1, k -> new ArrayList<>()).add(value1);
I am not sure if this is correct or if it will work as I have not tested it yet:: then why are you asking? Test your code and do experiments first. And read the javadoc.
– JB Nizet
Jun 29 at 21:38
I tested it, and @shmosel this is not a duplicate, the other post is adding to a list within a hashmap. I know how to do that. I am asking how do I print to console the full hashmap.
– Andy Chan
Jul 1 at 1:51
You should update your code example so it compiles (and builds a real example map). I think it was misleading people. It looked like you were asking how to fill the map as part of your question. I tried to clarify the question a little bit, but you should still fix the code example.
– Radiodef
Jul 1 at 2:35
mp.forEach((k, v) -> System.out.println(k + ": " + String.join(", ", v)));– shmosel
Jul 1 at 4:19
mp.forEach((k, v) -> System.out.println(k + ": " + String.join(", ", v)));
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
mp.computeIfAbsent(key1, k -> new ArrayList<>()).add(value1);– shmosel
Jun 29 at 21:38