Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 : Map Lambda expression

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?

like image 280
RanPaul Avatar asked Apr 27 '15 06:04

RanPaul


2 Answers

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());
like image 105
Eran Avatar answered Sep 23 '22 17:09

Eran


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.

like image 39
fge Avatar answered Sep 20 '22 17:09

fge