Java 8 : Map Lambda expression

14,451

Solution 1

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());

Solution 2

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…

Solution 3

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.

Share:
14,451
OTUser
Author by

OTUser

Updated on June 14, 2022

Comments

  • OTUser
    OTUser almost 2 years

    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?

  • fge
    fge almost 9 years
    This is typically a case where I personally think that a full stream solution is actually less readable than a "good old" foreach loop :p
  • Holger
    Holger almost 9 years
    Code simplification does not always need Stream API use…