Reputation: 725
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
Upvotes: 1
Views: 2143
Reputation: 2507
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;
}
Upvotes: 0
Reputation: 30088
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.
Upvotes: 1