在散列映射中搜索arraylist中的值

时间:2016-11-16 06:30:00

标签: java hashmap

我有一个使用ID作为键的hashmap,因为value有一个带有更多ID的arraylist。

我需要搜索一个ArrayList ID,但不需要知道密钥的ID。

你怎么做这个搜索?

EDITT:我需要在arraylist中查找一个数字而不知道它的hashmap键。

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

3 个答案:

答案 0 :(得分:3)

简单循环遍历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;
        }
    }
}

答案 1 :(得分:2)

我认为您的地图的类型为HashMap<Integer, List<Integer>>

HashMap<Integer, List<Integer>> yourMap = new HashMap<>();

要搜索值,请执行以下操作:(我在此示例中搜索1)

for (List<Integer> value : a.values()) {
    if (value.contains(1)) { // change the 1 to whatever value you're searching
        System.out.println("Found!");
    }
}

或者,使用stream

if (a.values().stream().filter(value -> value.contains(1)).count() > 0) {
    System.out.println("Found!");
}

答案 2 :(得分:0)

以下是Java 8流的解决方案。

  //Map<Integer, ArrayList<Integer>> map = new HashMap<>();//

  int targetVal = 31;
  Optional<Integer> val = map.entrySet()
            .stream()
            .filter(i -> i.getValue().contains(targetVal))
            .map(Map.Entry::getKey)
            .findFirst();

    System.out.println(val.isPresent() ? val.get() : null); 
相关问题