Simplify nested loop over map

JonB :

I'm sure I don't need the nested inner loop, but how can this be achieved with one loop, any loop will do, just wanna get rid of the nested loop.

for (List<GoogleUsageMapping> recordsMap : recordsGroupByMetadataId.values()) {
    for (GoogleUsageMapping record : recordsMap) {
        System.out.println(record.getUsage());
    }
}
Zabuza :

There is no way to get rid of it.

But you can of course hide it. It is still a nested loop in disguise though. Example:

recordsGroupByMetadataId.values()
    .stream()
    .flatMap(List::stream)
    .map(GoogleUsageMapping::getUsage)
    .forEach(System.out::println);

Stream::flatMap (documentation) puts multiple streams together into one big stream, that is what flattens the nested loops into one big loop.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142251&siteId=1