如何迭代具有k,v字符串和列表的hashmap?

时间:2016-02-08 12:58:02

标签: java dictionary hashmap

我有一个这样的散列图:

HashMap<String, List<String>> total=new HashMap<>();

现在我有了k,v的hashmap,我希望迭代并为每个键打印键所有的值,包括重复项,并且每个副本再次打印键,所以它看起来像这样:

123   john

123   tom

123   jack

234   terry

234   jeniffer

345   jacob

555   sara

3 个答案:

答案 0 :(得分:2)

for (Map.Entry<String, List<String>> entry : total.entrySet()) {
  for (String s : entry.getValue()) {
    System.out.println(entry.getKey() + " " + s);
  }
}

答案 1 :(得分:1)

假设以下设置:

    List<String> first = new ArrayList<>();
    first.add("a");
    first.add("b");
    List<String> second = new ArrayList<>();
    second.add("c");  
    second.add("d");
    HashMap<String, List<String>> total = new HashMap<>();
    total.put("First", first);
    total.put("Second", second);

在Java 8中,您可以使用forEach迭代hashmap的条目,并在每次迭代中检索键和值:

    total.forEach( (k, v) -> {
        System.err.printf("%s => %s\n",  k, v);
    });

输出:

Second => [c, d]
First => [a, b]

答案 2 :(得分:0)

使用Java 8,您可以迭代条目,然后遍历每个列表元素并打印结果:

total.entrySet()
    .stream()
    .forEach(entry -> {
        entry.getValue()
        .stream()
        .forEach(string -> System.out.println(entry.getKey() + " " + string));
    });

或更短,但在我看来不太清楚:

total.forEach((key, list) -> {
    list.forEach(value -> System.out.println(key + " " + value));
});