Joe Bauner Joe Bauner - 1 year ago 86
Java Question

How to rewrite java 7 code to java8 using lambda

How can I rewrite this code to java 8 using lambda ?

Iterator<Document> doc = documents.iterator();
while (doc.hasNext()) {
Document document =;
for(String docType : documentTypes) {
if (document.getDocumentType().equals(docType)){


Answer Source

If you wanted to filter out Document objects that don't have a desired docType, use Stream#filter:

List<Document> filteredDocs = documents
    .filter(doc -> documentTypes.contains(doc.getDocumentType()))

Or if you want to mutate documents, use Collection#removeIf:

documents.removeIf(doc -> !documentTypes.contains(doc.getDocumentType()));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download