Joe February 2016

How to iterate on hashmap that have k,v of string and list?

I have a hashmap like this:

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

and now I have hashmap with k,v and I want to iterate and print for each key the key all the values that it have including duplicates, and for each duplicate to print the key again, so it will look like this:

123   john

123   tom

123   jack

234   terry

234   jeniffer

345   jacob

555   sara

Answers


Andy Turner February 2016

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


Andreas Fester February 2016

Assumed the following setup:

    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);

In Java 8, you can use forEach to iterate over the entries of the hashmap and retrieve both key and value in each iteration:

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

Output:

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


Boris van Katwijk February 2016

With Java 8 you could iterate over the entries, then iterate over each list element and print the result:

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

Or shorter, but in my eyes less clear:

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

Post Status

Asked in February 2016
Viewed 1,854 times
Voted 13
Answered 3 times

Search




Leave an answer