Java 8: displaying a Lambda expression

I have a Map<String, List<Object>> multiFieldMap , and I need to Map<String, List<Object>> multiFieldMap over its value and add the value to multiFieldsList , as shown 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; } 

I wonder if this method can be simplified yet.

+5
source share
3 answers

You can use 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()); 
+5
source

You can really use a thread to simplify the 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); } 

from:

 entry.getValue().map( id -> queryService.query(entityName, queryService.property("id").eq(id)) ).forEach(multiFieldsList::add); 

But you don’t really win anything. Your choice...

See @Eran answer for a full flow solution.

+2
source

You can simplify it as follows:

 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; } 

If you don’t want to use the Stream API, the Map.forEach method may be the biggest victory in terms of simplifying the code, since you do not need to work with Map.Entry and its common signature anymore ...

+2
source

All Articles