JeremP
JeremP

Reputation: 47

Find element in Java HashMap<String, String[]>

I'm having trouble to find an element inside my String array contained inside my HashMap. I have a String that is indeed inside this String[] but doing the following does not work.

if (groupOuMap.containsValue("someString")) {
     groupOu = "someString";
} 

My goal is to find the corresponding key of my HashMap where the value is found.

Exemple with a sample of my map :

nedcard.nl -> ["Wijchen account"]
mic.ad ->  ["Ayutthaya4", "Brazil", "Changi", "Dresden", "Guangzhou"]

If I search for the String Brazil, I'd like to have a new Array of String which would be :

String[] groupOu = {"mic.ad", "Brazil"};

I have tried to used groupOuMap.values().contains() as well with no success.

Am I doing this wrong? Thank you!

Upvotes: 0

Views: 2293

Answers (2)

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

In Java the easiest way to do this is probably just to iterate through each key-value pair in the map, and search for the first occurrence of the search term in the array that is the value. When found, return both the key and the value. If not found, return null.

public static String[] keyContainingValue(HashMap<String, String[]> map, String searchFor) {
    for (String key : map.keySet()) {
        String[] values = map.get(key);
        // construct for replicating List.contains() on a primitive array
        if (Arrays.stream(values).anyMatch(i -> i.equals(searchFor))) {
            return {key, searchFor};
        }
    }
    return null;
}

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89224

You can filter over the entrySet via Streams.

public static String[] search(Map<String, String[]> map, String value){
    return map.entrySet().stream()
      .filter(e -> Arrays.stream(e.getValue()).anyMatch(value::equals))
      .findAny().map(e -> new String[]{e.getKey(), value}).orElse(null);
}
//...
Map<String, String[]> map = Map.of("mic.ad", new String[]{"Ayutthaya4", "Brazil", "Changi", "Dresden", "Guangzhou"}, "nedcard.nl", new String[]{"Wijchen account"});
System.out.println(Arrays.toString(search(map, "Brazil"))); // [mic.ad, Brazil]

Demo

Upvotes: 1

Related Questions