How to filter a Hashmap by returning another Hashmap using Java 8 lambda?

Asked

Viewed 133 times

5

The following code traverses a Set and filters only the objects that the isActive() is true.

public Set<InvoiceLineDocument> getActiveLines() {
        Set<InvoiceLineDocument> activeLines = new HashSet<>();

        for (InvoiceLineDocument lineDocument : lineDocuments) {
            if (lineDocument.isActive())
                activeLines.add(lineDocument);
        }

        return activeLines;
    }

How do I convert this implementation to Java 8 stream().filter()?

  • Invoicelinedocument is your class or some lib?

  • It’s a class of mine.

  • 3

    Have you tried with lineDocuments.stream().filter(x -> x.isActive()).collect(Collectors.toSet()); ?.

  • Gosh, I hadn’t seen toSet(). That’s right, it worked. It wouldn’t be better to create an answer to mark as "solved"?

2 answers

4


If you want to filter those that are active with stream and filter, only need to use the method isActive within the filter and accumulate the result in a set with toSet:

lineDocuments.stream().filter(x -> x.isActive()).collect(Collectors.toSet());

1

If I understand your doubt correctly just do the following:

Set<LineDocument> set = lineDocuments.stream().filter( l -> l.isActive()).collect(Collectors.toSet());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.