我有一个使用 ID 作为键的 hashmap,因为值有一个包含更多 ID 的数组列表。
我需要搜索 ArrayList ID,但不需要知道键的 ID。
您如何进行此搜索?
编辑:我需要在 arraylist 中查找一个数字,但不知道它的 hashmap 键。
最佳答案
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/