8

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?

3 Answers 3

6

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());
Sign up to request clarification or add additional context in comments.

1 Comment

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
2

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.

1 Comment

Code simplification does not always need Stream API use…
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…

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.