0

So I have a basic hashmap with an arraylist:

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

Say I have a key value pair: Key: Apple, Value: orange, red, blue

I already understand how to iterate through to print the key and it’s values like so: Apple, orange, red, blue

but is there a way to break up the values/iterate through the inner ArrayList and print the key/value pair three separate times/print the key with each value separately like:

Apple orange
Apple red
Apple blue
Dmitry Smorzhok
  • 635
  • 11
  • 21
Jane Dow
  • 27
  • 3
  • 1
    That shouldn't be difficult, put your solution and we will help – niemar Oct 06 '18 at 07:28
  • Possible duplicate of [Iterate through a HashMap](https://stackoverflow.com/questions/1066589/iterate-through-a-hashmap) – niemar Oct 06 '18 at 07:29

2 Answers2

3

You could use a nested loop:

for (Map.Entry<Text, ArrayList<Text>> entry : map.entrySet()) {
    for (Text text : entry.value()) {
        System.out.println(entry.key() + " " + text);
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
3

Using simple for loops, this would be:

for (Map.Entry<Text, ArrayList<Text>> entry : map.entrySet()) {
    for (Text text : entry.value()) {
        System.out.println(entry.key() + " " + text);
    }
}

Doing the same in a functional way:

map.forEach((key, valueList) ->
    valueList.forEach(listItem -> System.out.println(key + " " + listItem)
));
syntagma
  • 23,346
  • 16
  • 78
  • 134