View on GitHub

Jump from Java 7 to Java 8

After our team moved to java 8 (yes, it happened!), I’ve got the idea: “If I rewrite some pieces of one service using new powers of Java 8..”

For example, we have some method, which on the base of documents aggregates common imformation according to them. Here’s what old style looked like:

public List<Document> getDocumentsStatistics(List<Document> documents)
    final List<Document> documentsStatistics = new ArrayList();
    for (Document document : documents) {
        final List<DocumentHashType> types = new ArrayList<DocumentHashType>();
        for (DocumentHashType type : document.getDocumentType())
            types.add(type);
        DocumentStatistics documentStatistics = 
        	new DocumentStatistics(
                        document.getName(),
                        document.getLocation(),
                        document.getSourceId(),
                        types,
                        document.getDateCreated());
        documentsStatistics.add(documentStatistics);
    }
    return documentsStatistics;
}

This method in new style:

private List<DocumentStatistics> getDocumentsStatistics(Collection<Document> documents) {
   return new ArrayList<DocumentStatistics>(
           documents
               .stream()
               .map(x -> new DocumentStatistics(
                        x.getName(),
                        x.getLocation(),
                        x.getSourceId(),
                        x.getDocumentHashTypes()
                            .stream()
                            .collect(Collectors.toList()),
                        x.getDateCreated()))
               .collect(Collectors.toList()));

Not bad. More briefly, avoid mutable state.

Next, we need take group for id. Early we did it so:

public DocumentGroup getDocumentGroupById(String id) {
        for (Map.Entry<String, DocumentGroup> group:
        	documentGroups.entrySet()) {
            if (group.getValue().getGroupId().getId() == id)
                return group.getValue();
        }
        return null;
    }

Let’s convert it:

final DocumentGroup documentGroup = 
	service.getKnowledgeBase()
                .getDocumentGroups()
                .stream()
                .filter(x ->
               	  x.getGroupId().getId() == id)
                .findFirst()
                .get();