Reputation: 3848
I have a Map<String, List<Object>> multiFieldMap
and I need to itereate over its value set and add the value to multiFieldsList
as below
public List<Object> fetchMultiFieldsList() {
List<Object> multiFieldsList = new ArrayList<Object>();
for (Entry<String, List<Object>> entry : multiFieldMap.entrySet()) {
String entityName = entry.getKey();
List<Object> ids = entry.getValue();
for (Object id : ids) {
Object entity = queryService.query(entityName, queryService.property("id").eq(id));
multiFieldsList.add(entity);
}
}
return multiFieldsList;
}
Am wondering can this method be simplified further?
Upvotes: 8
Views: 27159
Reputation: 298143
You can simplify it like this:
public List<Object> fetchMultiFieldsList() {
List<Object> multiFieldsList = new ArrayList<>();
multiFieldMap.forEach( (entityName, ids ) ->
ids.forEach( id -> multiFieldsList.add(
queryService.query(entityName, queryService.property("id").eq(id)))
)
);
return multiFieldsList;
}
Unless you want to use the Stream
API, the method Map.forEach
might be the biggest win regarding code simplification as you don’t need to deal with Map.Entry
and its generic signature anymore…
Upvotes: 2
Reputation: 393801
You can use the Streams API :
List<Object> multiFieldsList =
multiFieldMap.entrySet()
.stream()
.flatMap(e -> e.getValue()
.stream()
.map(o -> queryService.query(e.getKey(), queryService.property("id").eq(o))))
.collect(Collectors.toList());
Upvotes: 6
Reputation: 121710
You can indeed use a stream to simplify you inner loop.
You can replace:
List<Object> ids = entry.getValue();
for (Object id : ids) {
Object entity = queryService.query(entityName, queryService.property("id").eq(id));
multiFieldsList.add(entity);
}
with:
entry.getValue().map(
id -> queryService.query(entityName, queryService.property("id").eq(id))
).forEach(multiFieldsList::add);
But you don't really gain much from that. Your choice...
See @Eran's answer for a "full stream" solution.
Upvotes: 2