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?
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With