java - 在 HashMap 中的数组列表中搜索值

标签 java hashmap

我有一个使用 ID 作为键的 hashmap,因为值有一个包含更多 ID 的数组列表。

我需要搜索 ArrayList ID,但不需要知道键的 ID。

您如何进行此搜索?

编辑:我需要在 arraylist 中查找一个数字,但不知道它的 hashmap 键。

示例: enter image description here 验证20是否存在,如果为真,返回3333

最佳答案

HashMap 的简单循环:

public static void main(String[] args) {
    Integer needle = 20;

    HashMap<Integer, ArrayList<Integer>> hm = new HashMap<Integer, ArrayList<Integer>>();
    hm.put(1111, new ArrayList<Integer>());
    hm.get(1111).add(1);
    hm.get(1111).add(2);
    hm.get(1111).add(3);
    hm.get(1111).add(4);
    hm.get(1111).add(5);
    hm.get(1111).add(6);

    hm.put(2222, new ArrayList<Integer>());
    hm.get(2222).add(8);
    hm.get(2222).add(10);
    hm.get(2222).add(11);

    hm.put(3333, new ArrayList<Integer>());
    hm.get(3333).add(15);
    hm.get(3333).add(19);
    hm.get(3333).add(20);
    hm.get(3333).add(31);

    for (Entry<Integer, ArrayList<Integer>> entry : hm.entrySet()) {
        ArrayList<Integer> v = entry.getValue();
        if (v.contains(needle)){
            System.out.println(entry.getKey());
            break;
        }
    }
}

关于java - 在 HashMap 中的数组列表中搜索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40625458/

相关文章:

java - 使用 bcel 时构造方法的堆栈图

java - 是否存在 Java 7's Hashmap implementation is preferred to Java8' s 实现的场景

java - 如何使用 map 根据不同参数搜索员工对象列表?

javascript - typescript 创建新 map <String, List<String>>

java - 在 map java流列表中查找 map

java - 在内存中创建了多少个字符串?

java - 如何自定义JSessionID

java - 如何更改 weblogic 10.3 (10gR3) 中的 java 版本?

java - 在 Socket 中正确处理 chunked Http Response

Perl 需要很长时间来评估 : keys %hash/iterate through a large hash