Joe Bauner Joe Bauner - 1 month ago 15
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 = doc.next();
for(String docType : documentTypes) {
if (document.getDocumentType().equals(docType)){
break;
}
}
doc.remove();
}


thanks

Answer

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

List<Document> filteredDocs = documents
    .stream()
    .filter(doc -> documentTypes.contains(doc.getDocumentType()))
    .collect(Collectors.toList());

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

documents.removeIf(doc -> !documentTypes.contains(doc.getDocumentType()));