How to filter a HashMap returning another HashMap using Java 8 lambda?

4

The following code runs through Set and filters only objects that 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() ?

    
asked by anonymous 15.05.2018 / 20:15

2 answers

4

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

lineDocuments.stream().filter(x -> x.isActive()).collect(Collectors.toSet());
    
15.05.2018 / 20:31
1

If I understand your question correctly, you simply do the following:

Set<LineDocument> set = lineDocuments.stream().filter( l -> l.isActive()).collect(Collectors.toSet());
    
15.05.2018 / 20:35