简体   繁体   中英

Iterate over Hashmap<String, ArrayList<String>>

How can i iterate over a Hashmap<String, ArrayList<String>> which looks like those?

Name:Sam,Peter,Andrea,Sandra
Age:20,17,24,40
City:London,London,Munich,London

The result should look like this four arrays.

Sam,20,London 
Peter,17,London 
Andrea,24,Munich 
Sandra,40,London

I've tried with two for(...) loops again and again, but it doesn't work.

Best regards :D

If this is something that you've written, then I'd like to suggest an alternate data structure. Instead of Hashmap<String, ArrayList<String>> , use ArrayList<HashMap<String, String>>

so that you have

{Name:Sam,    Age:20, City:London},
{Name:Peter,  Age:17, City:London},
{Name:Andrea, Age:24, City:Munich},
{Name:Sandra, Age:40, City:London}

If the HashMap of Lists is not something that you've written, and you still need help to figure out how to iterate that, please show us what you have tried.

Though I absolutely agree with @GreyBeardedGeek in his answer, and you should probably change your data structure. I did however have a look at the code needed to change Map<String, List<String>> into List<Map<String, String>>

public static <S, T> List<Map<S, T>> unravel(Map<S, List<T>> org) {
    List<Map<S, T>> out = new LinkedList<>();

    for (Entry<S, List<T>> entry : org.entrySet()) {
        if (entry.getValue() == null || entry.getValue().isEmpty()) {
            continue;
        }
        while (out.size() < entry.getValue().size()) {
            out.add(new HashMap<S, T>());
        }
        for (int i = 0, size = entry.getValue().size(); i < size; i++) {
            T value = entry.getValue().get(i);

            if (value == null) {
                continue;
            }

            out.get(i).put(entry.getKey(), value);
        }
    }

    return out;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM