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
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);
}
}
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)
));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.