Check if a List is a value in a HashMap

java hashmap check if value exists
check if key value pair exists in hashmap java
how to check if something is in a hashmap java
java hashmap check if key exists
hashmap containskey and contains value
how to compare single hashmap values in java
java check if value exists
best way to iterate hashmap in java

I want to check if a value exists.

My Code:

public static final Map<String, List<String>> m = new HashMap<>();

if(m.containsValue("gummi")) {...}

My problem is that the value is a List. How can I check for the List?

So I am going to interpret the question, as wanting to tell whether any value of the Map contains the target String.

There's probably a more appropriate third-party bi-direction multimap implementation. If you are reading this in the future such a type may be in Java SE - please edit this answer.

Given the data structures, this is going to require searching through the entire data. It may be better to have Map mapping the other way. Let's ignore that.

The streams one-liner expression solution:

m.values().stream().anyMatch(list -> list.contains("gummi"))

Edit: For Horse Voice, a non-stream version.

flatContains(m.values(), "gummi")

where

public static boolean flatContains(
    Iterable<? extends Collection<?>> collections,
    Object value
) {
    for (Collection<?> collection : collections) {
        if (collection.contains(value)) {
            return true;
        }
    }
    return false;
}

Often avoiding streams makes for more readable code (and faster). However, in this case, I would go straight for the streams. If flatMap was involved, the choice would be much closer.

Java, In this example we are checking whether a particular value exists in HashMap or not. We will be using containsValue() method of HashMap class to perform. You need to first try to retrieve an existing key in the map, and if it already exists (i.e., was inserted for a previous input line), then you can append the current name to its value, and re-insert it into the map. Also, you're probably going to want to use something like List<String> to hold the map values (the names) instead of just a String.

Map<String, List<String>> m = new HashMap<>();

    List<String> list1 = new ArrayList<>();
    List<String> list2 = new ArrayList<>();
    List<String> list3 = new ArrayList<>();

    m.put("1", list1);
    m.put("2", list2);

    System.out.println(m.containsValue(list1));
    System.out.println(m.containsValue(list2));
    System.out.println(m.containsValue(list3));

Output

true
true
true

Explanation

As long as the new list is empty, the hashcode value is always 1. So list1,list2 and list3 will all have the hashcode value of 1. Basically meaning,

list1 = list2 = list3

So even if we check m.containsValue(list3); it will return true. But if the list is not empty, each list will have a unique hashcode. So as long as you have a map with non-empty lists then we could use containsValue(listObject) which will return correct result. Example below,

Map<String, List<String>> m = new HashMap<>();

    List<String> list1 = new ArrayList<>();
    List<String> list2 = new ArrayList<>();
    List<String> list3 = new ArrayList<>();

    list1.add("apple");
    list1.add("orange");

    list2.add("mobile");
    list2.add("computer");

    m.put("1", list1);
    m.put("2", list2);

    System.out.println(m.containsValue(list1));
    System.out.println(m.containsValue(list2));
    System.out.println(m.containsValue(list3));

Output:

true
true
false

Other use cases:

If we want to check whether the value in the map is of type list or we would like to check a value is present in one of the list, then we can iterate the map as below,

for (String key : m.keySet()) {
        if (m.get(key) instanceof List) {
            for (String listItem : m.get(key)) {
                if ("valueWeSearchFor".equalsIgnoreCase(listItem)) {
                    break;
                }
            }
        }else{
            //If the value in the map is not of type list
            //What to do!!
        }
    }

HashMap containsValue() Method in Java, HashMap.containsValue() method is used to check whether a particular value is Return Value: The method returns boolean true if the mapping of the value is� Java – Check if a particular value exists in HashMap example. In this example we are checking whether a particular value exists in HashMap or not. We will be using containsValue () method of HashMap class to perform this check: public boolean containsValue (Object value): Returns true if this map maps one or more keys to the specified value.

Java 7: contains for Map<String, List<String>>

Assuming the same as Tom, here is a Java 7 version (as requested by Horse Voice):

// Live version
static boolean contains(Map<String, List<String>> map, String value) {
    for (List<String> list : map.values()) {
        if(list.contains(value)) return true;
    }
    return false;
}

If your source Map doesn't change, it might be better to create a search cache:

// Cached version
private List<String> allValues = getInnerValues(map);
private List<String> getInnerValues(Map<String, List<String>> map) {
    List<String> result = new ArrayList<>();
    for (List<String> list : map.values()) {
        result.addAll(list);
    }
    return result;
}

static boolean contains(String value) {
    return allValues.contains(value);
}
Java 7: anyKeyForValue and keysForValue

I figure some people will want the key(s) that match the value:

// Live version
static String anyKeyForValue(Map<String, List<String>> map, String value) {
    for (Entry<String, List<String>> entry : map.entrySet()) {
        if(entry.getValue().contains(value)) return entry.getKey();
    }
    return null;
}

static List<String> keysForValue(Map<String, List<String>> map, String value) {
    List<String> result = new ArrayList<>();
    for (Entry<String, List<String>> entry : map.entrySet()) {
        if(entry.getValue().contains(value)) result.add(entry.getKey());
    }
    return result;
}

Caching is a little harder; we need to invert the Map:

// Cached version
private Map<String, List<String>> valueKeys = invert(map);
private Map<String, List<String>> invert(Map<String, List<String>> map) {
    Map<String, List<String>> result = new HashMap<>();
    for (Entry<String, List<String>> entry : map.entrySet()) {
        for (value : entry.getValue()) {
            List<String> keys;
            if (result.containsKey(value)) {
                keys = result.get(value);
            } else {
                keys = new ArrayList<String>();
                result.put(value, keys);
            }
            keys.add(entry.getKey());
        }
    }
    return result;
}

static List<String> keysForValue(String value) {
    return valueKeys.get(value);
}

How to check if a key exists in a HashMap in Java, The entry key of the Map can be obtained with the help of entry.getKey() method. If the key matches, set the flag as true. The flag value after iterating, contains the� The java.util.HashMap.values() method of HashMap class in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap. Syntax: Hash_Map.values() Parameters: The method does not accept any parameters.

I think Surender Kherwa' answer qualifies, but I think when you look for an element in a collection it's better to use while loop instead of for, here's the example (for java 7) :

String gummi = "gummi";
Map<String,List<String>> map = new HashMap<String,List<String>>() {
{

put("KEY1", new ArrayList<String>(){{
    add("check");
    add("if");
    add("a");
    add("list");
    add("is");
}});

put("KEY2", new ArrayList<String>(){{
    add("a");
    add("gummi");
    add("value");
    add("in");
    add("a");
}});

put("KEY3", new ArrayList<String>(){{
    add("HashMap");
    add("java");
    add("7");
    add("while");
    add("loop");
    add("version");
}});

}};

Iterator<Map.Entry<String, List<String>>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
  Map.Entry<String, List<String>> entry = iterator.next();
  if (entry.getValue().contains(gummi)) {
    System.out.println("Found in : " + entry.getKey());
    break;
  }
}

Java HashMap ContainsKey and ContainsValue , Java HashMap ContainsKey and ContainsValue Example - Check if a Key or Value exists in the Map 8 (tutorial); How to convert List to Map in Java 8 ( solution); Difference between abstract class and interface in Java 8? Check if the key exists in the HashMap or not using HashMap.containsKey () method. If the key exists, set the flag as true. The flag value, contains the result. Below is the implementation of the above approach:

@Tom's answer is the best however, @HorseVoice asked for Java 7 version, which is as below:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * https://stackoverflow.com/questions/32925049/check-if-a-list-is-a-value-in-a-hashmap
 *
 * @author surender.kumar
 */
public class CheckListValueInHashMapExists {

    public static final Map<String, List<String>> m = new HashMap<>();

    public static void main(String[] args) {
        System.out.println("Running main ...");
        initM();
        String gummi = "gummi";

        System.out.println("Do the list contains value gummi? " + checkValueExistsJava7());
    }

    private static boolean checkValueExistsJava7() {
        for (List<String> list : m.values()) {
            if (list.contains("gummi")) {
                return true;
            }
        }
        return false;
    }

    private static void initM() {
        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        list1.add("value1a");
        list1.add("value1b");
        list2.add("value2");
        list2.add("gummi");
        m.put("1", list1);
        m.put("2", list2);
    }
}

Output:

Running main ...
Do the list contains value gummi? true

How to Check if a Key Object Exists in HashMap Java? containsKey , How do HashMap checks if a key object exists or not. Here is a diagram which shows how HashMap is structured internally on an array, called bucket. When you� Collection values(): It is used to return a Collection view of the values in the HashMap. compute(K key, BiFunction<K, V> remappingFunction) : This method Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).

How to check if a HashMap is empty or not?, public boolean isEmpty() : According to Oracle docs, this method returns true if the map contains no key-value mappings. Program for How to Check if a HashMap� And another thing is that you should use the List interface as type, so you are able to change the implementation (ArrayList or whatever) in the future. Here the corrected code: Map mMap = new HashMap(); List<Map> list = new ArrayList();

Java Hashmap - Check if Key/Value Exists in Map, Java Hashmap – containsKey(Object key) and containsValue(Object value) – Check if Key/Value Exists in Map. Last Updated on December� The get method of the HashMap class returns the value mapped to a given key in the map. If the key is not mapped to any value in the map, it returns null. 1. public V get(Object key) You can compare the return value with null to check if the HashMap has the key. 1.

Java Program to check if a given value exists in a HashMap, Use the containsValue() method to check if a given value exists or not in a HashMap.First, let us create a HashMap and add some elements� The java.util.HashMap.containsValue () method is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. It takes the Value as a parameter and returns True if that value is mapped by any of the key in the map.

Comments
  • Any update on this? This is a pretty interesting problem to solve. Tunaki is taking a shortcut by assuming caller of the method knows the items in the list and that defeats the purpose. the questioner is asking something entirely different.
  • @HorseVoice What would you say that the OP is asking, exactly? It's still not clear to me. Are they asking if any List in the Map contains "gummi", or are they asking if there exists a List in the Map that only contains "gummi"? I'd be happy to write an answer that caters to both situations.
  • I guess the former; does any list contain "gummi"?
  • @HorseVoice - Here's a Java 7 version (as requested): stackoverflow.com/questions/32925049/…
  • The question in itself is unclear. To check if the value exists, one would want to check for a similar type. As close as it could be interpreted based on the answers, it should read if an object exists in any of the values of the Map...
  • can you give the same answer in java 7 not including lambdas?
  • @HorseVoice: Added Java 7 version here: stackoverflow.com/a/58871387/2015408
  • Or perform a flatMap to avoid contains over a list, m.values().stream().flatMap(Collection::stream).anyMatch(str -> str.equals("gummi"))
  • @Naman You could, but I don't think there would be much advantage in this case. flatMap makes it less clear and, I think, the performance will be worse. It does, however, allow you to switch the predicate to something more interesting.
  • i think this code is right answer, have you tried this code @max
  • I don't understand why you think the while loop is better. Not unless you were going for some kind of SESE (Single Entry Single Exit) style: while (iterator.hasNext() && (entry = iterator.next()).getValue().equals(gummi)) {. (Not a style I particularly like, but see where it is coming from, but not particularly helpful here.)
  • In addition to previous comment. Don't use double-bracket initialization, we don`t need useless anonymous classes.
  • If you're not going to cache, then you should definitely be short-circuiting when you find a match! You might find "gummi" in the first list!