How to compare 2 different Hashmaps in Java

Asked

Viewed 27 times

0

I have 2 Strings that convert to Hashmaps, the first is an input that the user gives to the application. The second is an Array that contains a lot of words.

I need to compare both Hashmaps to see if the input can be rearranged to match one of the words in the Array. There is no need to use every char of the user input to the system, there may be some char left over from the first Hashmap, but I need to make sure that they can match one of the words in the Array (the second Hashmap).

This is the code to create the first Hashmap:

String normalizedInputWord = normalizeString(inputWord);

Map<Character, Integer> countDuplicateMapInput = new HashMap<>();

char[] charInputArray = normalizedInputWord.toCharArray();

for (char c: charInputArray) {
    if (countDuplicateMapInput.containsKey(c)) {
        countDuplicateMapInput.put(c, countDuplicateMapInput.get(c) + 1);
    } else {
        countDuplicateMapInput.put(c, 1);
    }
}

This is the second Hashmap:

Map<Character, Integer> countDuplicateMapArray = new HashMap<>();

for (int i = 0; i < 1; i++) {
    // Chama uma função para normalizar cada String do Array wordArray
    String normalizedWordArray = normalizeString(wordArray[i]);

    char[] charWordArray = normalizedWordArray.toCharArray();

    for (char c : charWordArray) {
        if (countDuplicateMapArray.containsKey(c)) {
            countDuplicateMapArray.put(c, countDuplicateMapArray.get(c) + 1);
        } else {
            countDuplicateMapArray.put(c, 1);
        }
    }
}

How can I compare these 2 structures and get a "true" response to the example below?

Example: Input is "unstoppable" and Hashmap countDuplicateMapInput will receive:

{
key: "p", value: 2;
key: "a", value: 1;
key: "b", value: 1;
key: "s", value: 1;
key: "t", value: 1;
key: "u", value: 1;
key: "e", value: 1;
key: "l", value: 1;
key: "n", value: 1;
key: "o", value: 1;
}

and has the word "stop" in my Array that will popular the Hashmap countDuplicateMapArray as follows:

{
key: "p", value: 1;
key: "t", value: 1;
key: "s", value: 1;
key: "o", value: 1;
}

1 answer

0

I found an answer that solved my problem and I’ll leave it on record here in case someone is having the same problem.

countDuplicateMapArray.entrySet().stream()
     .allMatch(e -> countDuplicateMapInput.getOrDefault(e.getKey(), 0) >= e.getValue());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.