kvm006
kvm006

Reputation: 5343

Java 8 Stream implementation for nested documents returned from MongoDB

I have a MongoDB collection of nested documents as follows. I am trying to read the tags in TestCase object. Right now my implementation is really basic with 4 for loops. I am new to java8 and I would like to use streams or any simple approach to read the nested datasets.

class TestResults {
        public String ID;   
        DateTime timeStamp;
        List<TestCapability> testCapability;
}

class TestCapability {
        public String ID;   
        DateTime timeStamp;
        List<TestSuite> testSuite;
}

class TestSuite {
        public String ID;   
        DateTime timeStamp;
        List<TestCase> testCase;
}

class TestCase {
        public String ID;   
        DateTime timeStamp;
        List<TestSteps> testSteps;
        private Set<String> tags = new HashSet<>();
}

my current implementation is very bad as follows

    for (TestResult testResult : testResults) {
        for (TestCapability capability : testResult.getTestCapabilities()) {
            for (TestSuite testSuite : capability.getTestSuites()){
                for (TestCase testCase : testSuite.getTestCases()) {
                    for (Feature feature : featureDetails) { 
                        if (testCase.getTags().contains(feature.getsNumber())){
                            testResultsAuditResponse.setsId(feature.getsId());
                            testResultsAuditResponse.setsNumber(feature.getsNumber());
                            testResultsAuditResponse.setsName(feature.getsName());
                            testResultsAuditResponse.setsStatus(feature.getsStatus());
                        }
                    }
                }
            }
        }
    }

Upvotes: 0

Views: 301

Answers (1)

Johannes Kuhn
Johannes Kuhn

Reputation: 15192

The answer is to use flatMap:

testResults.stream()
    .map(TestResult::getTestCapabilities).flatMap(Collection::stream)
    .map(TestCapability::getTestSuites).flatMap(Collection::stream)
    .map(TestSuite::getTestCases).flatMap(Collection::stream)
    .forEach(testCase -> {
        featureDetails.stream()
            .filter(feature -> testCase.getTags().contains(feature.getsNumber()))
            .map(Feature::getsId)
            .forEach(testResultsAuditResponse::setsId);
    });

Upvotes: 1

Related Questions