Skip to content
Advertisement

How to insert multiple keys with the same value into a hash map in Java?

I am doing the following coding challenge in java:

JavaScript

My idea is to insert all these letters in a hash map by doing something like this:

JavaScript

Is there any way to do this in java?

Advertisement

Answer

You said in your comments that you would like to be able to add all these entries in a single statement. While Java is not a great language for doing things like this in a single statement, it can be done if you are really determined to do so. For example:

JavaScript

Output:

C = 3

In the code above, I first build a stream of all the entries (as Pairs), and collect them into a map.

Note:

The Pair class I have used above is from javafx.util.Pair. However you could just as easily use AbstractMap.SimpleEntry, your own Pair class, or any collection data type capable of holding two Objects.


A Better Approach

Another idea would be to write your own helper method. This method could be put into a class which contains similar helper methods. This approach would be more idiomatic, easier to read, and thus easier to maintain.

JavaScript

Then you would use it like this:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement