I got a forms list, and it has a tags list. I received from my front end app an array of tags (String), gotta filter these forms by these tags.

forms.forEach(form -> {
    br.com.softplan.ungp.dynamic.form.api.model.Form formJson = new Gson()
            .fromJson(form.getSchema(), br.com.softplan.ungp.dynamic.form.api.model.Form.class);

    tags.forEach(tag -> formJson.getTags().forEach(formTag -> {
        if (tag.toUpperCase().equals(formTag.getText().toUpperCase())) {
            if (map.containsKey(tag)) {
                List<FormSummary> list = new ArrayList<>(map.get(tag));
                list.add(new FormSummary(form.getId(), form.getName()));
            } else {
                map.put(tag, Collections.singletonList(new FormSummary(form.getId(), form.getName())));

This code is already working as expected. I just want to improve it, writing less code using Java utilities.

What I was trying to do is to map all the result inside a map into its own iteration, using stream.map() or the Collectors.toMap(), but couldn't achieve what I wanted.


closed as off-topic by πάντα ῥεῖ, Stephen Rauch, Dannnno, Mast, t3chb0t Oct 9 '18 at 14:08

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – πάντα ῥεῖ, Dannnno, Mast
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    \$\begingroup\$ The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly. \$\endgroup\$ – Jamal Oct 9 '18 at 4:38

Your code is not easy to understand. However, you might replace the inner if-else construct with

map.computeIfAbsent(tag, t -> new ArrayList<>())
   .add(new FormSummary(form.getId(), form.getName()));

for brevity.

Note that the nested forEach will probably give you \$O(|\mathrm{forms}| \cdot |\mathrm{tags}|)\$ time complexity which could be a problem if forms or tags contains many elements.

  • \$\begingroup\$ Thanks! I didn't know this computeIfAbsent method, really helped. About the complexity, I know, this is not the way it's gonna be, just a temporary solution. I reorganized my code, it's more readable now. \$\endgroup\$ – Yan Rocha Oct 8 '18 at 19:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.