[英]Iterate through a hashmap with an arraylist?
So I have a basic hashmap with an arraylist: 所以我有一个带有arraylist的基本哈希图:
Map<Text, ArrayList<Text>> map = new HashMap<Text, ArrayList<Text>>();
Say I have a key value pair: Key: Apple, Value: orange, red, blue 假设我有一个键值对:键:Apple,值:橙色,红色,蓝色
I already understand how to iterate through to print the key and it's values like so: Apple, orange, red, blue 我已经了解了如何遍历以打印密钥,其值如下:Apple,橙色,红色,蓝色
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: 但是有一种方法可以拆分值/通过内部ArrayList迭代并分别打印键/值对三个时间/分别打印每个值的键,例如:
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
循环,将是:
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)
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.