ParweizH
ParweizH

Reputation: 67

Find matching key/value pairs in Hashmap

Suppose this is my hashmap:

HashMap<String,String> map = new HashMap<>();
map.put("animal", "Golden Retriever");
map.put("size", "big");
map.put("color","light golden");

By the help of this Stack Overflow answer I figured out how to get one specific matching element key-value pair by passing the key-value testdata and the map itself to the function.

Now, I'd like to extend the functionality so that the app takes more than one key-value pairs as parameter and still figure out if there's any matching element.

I suppose that the way I could handle this task is to first change the parameters to the function so that it takes two hashmaps instead. In here there would be eventually a loop which runs the testdata over the original hashmap and see if there is any matching element or not.

What is the best way to deal with this task?

Upvotes: 1

Views: 5155

Answers (2)

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

You can check whether your data map's entries contains one of your search map's entries using a stream:

import java.util.HashMap;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
        Map<String, String> data = new HashMap<>();
        data.put("animal", "Golden Retriever");
        data.put("size", "big");
        data.put("color", "light golden");


        Map<String, String> search = new HashMap<>();
        search.put("size", "small");
        search.put("color", "light golden");

        boolean matches = search.entrySet()
                .stream()
                .anyMatch(it -> data.entrySet().contains(it));

        System.out.println(matches);
    }
}

This works by virtue of Map.Entry.equals() being defined in terms of key and value equality.

Your utility method could look as follows:

public static <T, U> boolean matches(Map<T, U> data, Map<T, U> search) {
    return search.entrySet()
            .stream()
            .anyMatch(it -> data.entrySet().contains(it));
}

Upvotes: 0

Mike B
Mike B

Reputation: 2776

You can pass two HashMaps and loop through one and check if there is a match in the other one.
Method takes in haystack as the one to check for any needles in it. Returns boolean accordingly

public boolean ifContains(HashMap<String, String> haystack, HashMap<String, String> needles) {
    for (String key : haystack.keySet()) {
        if (needles.containsKey(key) && needles.get(key).equals(haystack.get(key))) {
            return true;
        }
    }
    return false;
}

Upvotes: 2

Related Questions