猿问

使用数组列表遍历哈希图?

所以我有一个带有数组列表的基本哈希图:


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

假设我有一个键值对:键:苹果,值:橙色、红色、蓝色


我已经了解如何迭代以打印密钥及其值,如下所示:Apple、orange、red、blue


但是有没有办法通过内部 ArrayList 分解值/迭代并将键/值对打印三次/分别打印每个值的键,例如:


Apple orange

Apple red

Apple blue


森栏
浏览 115回答 2
2回答

婷婷同学_

您可以使用嵌套循环:for (Map.Entry<Text, ArrayList<Text>> entry : map.entrySet()) {&nbsp; &nbsp; for (Text text : entry.value()) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(entry.key() + " " + text);&nbsp; &nbsp; }}

牛魔王的故事

使用简单的for循环,这将是:for (Map.Entry<Text, ArrayList<Text>> entry : map.entrySet()) {&nbsp; &nbsp; for (Text text : entry.value()) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(entry.key() + " " + text);&nbsp; &nbsp; }}以功能方式做同样的事情:map.forEach((key, valueList) ->&nbsp; &nbsp; valueList.forEach(listItem -> System.out.println(key + " " + listItem)));
随时随地看视频慕课网APP

相关分类

Java
我要回答