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:

/**
     * 4. Given a word, compute the scrabble score for that word.
     * 
     * --Letter Values-- Letter Value A, E, I, O, U, L, N, R, S, T = 1; D, G = 2; B,
     * C, M, P = 3; F, H, V, W, Y = 4; K = 5; J, X = 8; Q, Z = 10; Examples
     * "cabbage" should be scored as worth 14 points:
     * 
     * 3 points for C, 1 point for A, twice 3 points for B, twice 2 points for G, 1
     * point for E And to total:
     * 
     * 3 + 2*1 + 2*3 + 2 + 1 = 3 + 2 + 6 + 3 = 5 + 9 = 14
     * 
     * @param string
     * @return
     */

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

map.add({A,,E,I,O,U,L,N,R,S,T}, 1);

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:

Map<Character, Integer> scores =
    Stream.of("AEIOULNRST=1","DG=2","BCMP=3","FHVWY=4" /* etc */ )
        .flatMap(line -> line.split("=")[0].chars().mapToObj(c -> new Pair<>((char)c, Integer.parseInt(line.split("=")[1]))))
        .collect(Collectors.toMap(Pair::getKey, Pair::getValue));

System.out.println("C = " + scores.get('C'));

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.

public enum MapHelper {
; // Utility class for working with maps
public static <K,V> void multiKeyPut(Map<? super K,? super V> map, K[] keys, V value) {
for(K key : keys) {
    map.put(key, value);
}}}

Then you would use it like this:

Map<Character, Integer> scores = new HashMap<>();
MapHelper.multiKeyPut(scores, new Character[]{'A','E','I','O','U','L','N','R','S','T'}, 1);
MapHelper.multiKeyPut(scores, new Character[]{'D','G'}, 2);
MapHelper.multiKeyPut(scores, new Character[]{'B','C','M','P'}, 3);
/* etc */
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement