Optimize method to iterate to over Map> I have a Map&lt;String, List&lt;Object&gt;&gt; multiFieldMap and I need to iterate over its value set and add the value to multiFieldsList:

public List&lt;Object&gt; fetchMultiFieldsList() {
    List&lt;Object&gt; multiFieldsList = new ArrayList&lt;&gt;();
    for (Entry&lt;String, List&lt;Object&gt;&gt; entry : multiFieldMap.entrySet()) {
        String entityName = entry.getKey();
        List&lt;Object&gt; ids = entry.getValue();
        for (Object id : ids) {
            Object entity = queryService.query(entityName, queryService.property("id").eq(id));
            multiFieldsList.add(entity);
        }
    }
    return multiFieldsList;
}


Can this method be simplified further?
You can accomplish this using Java 8 streams.

public List&lt;Object&gt; fetchMultiFieldsList() {
    return multiFieldMap.entrySet().stream()
      .flatMap(e -&gt; {
          String entityName = e.getKey();
          List&lt;Object&gt; ids = e.getValue();
          return ids.stream()
            .map(id -&gt; queryService.query(entityName, queryService.property("id").eq(id)));
      }).collect(Collectors.toList());
}


I think the code itself is relatively self-explanatory. The important bit is the usage of flatMap instead of map for the first mapping operation so that the resulting streams are concatenated, ending up with a flat list of objects rather than a list of lists.

It is unfortunate that Java does not support destructuring assignment, which would allow the first lambda expression to be a single expression of the form (k, v) -&gt; ..., but it does not, so I've left the statements in for clarity.

If you are willing to omit the inner declarations, the above code can be simplified further.

public List&lt;Object&gt; fetchMultiFieldsList() {
    return multiFieldMap.entrySet().stream()
      .flatMap(e -&gt; e.getValue().stream()
          .map(id -&gt; queryService.query(e.getKey(), queryService.property("id").eq(id)))
      ).collect(Collectors.toList());
}


Whichever one you prefer is a matter of personal preference. The former has more descriptive variable names, while the latter is simpler and more functional.