Iterate through a hashmap with an arraylist?

血红的双手。 提交于 2019-12-11 16:54:41

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/52676712/iterate-through-a-hashmap-with-an-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!