检查列表是否为HashMap中的值

Max*_*Max 11 java list hashmap

我想检查一个值是否存在。

我的代码:

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

if(m.containsValue("gummi")) {...}
Run Code Online (Sandbox Code Playgroud)

我的问题是值是一个列表。如何检查清单?

Tom*_*ine 13

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"))
Run Code Online (Sandbox Code Playgroud)

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

flatContains(m.values(), "gummi")
Run Code Online (Sandbox Code Playgroud)

where

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

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.


Tun*_*aki -1

引用List.equalsJavadoc:

换句话说,如果两个列表包含相同顺序的相同元素,则它们被定义为相等。

因此,要检查某个值是否存在,您可以创建一个列表并调用containsValue该列表List,因为该方法将调用equals以确定相等性。如果相同的元素具有相同的顺序,则会找到匹配项。

List您可以使用以下命令轻松地从值数组创建Arrays.asLista :

if(m.containsValue(Arrays.asList("gummi"))) {...}
Run Code Online (Sandbox Code Playgroud)

示例代码:

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

list.add("1");
list.add("2");
m.put("key", list);

if (m.containsValue(Arrays.asList("1", "2"))) {
    System.out.println("contains value");
}
Run Code Online (Sandbox Code Playgroud)