jeudi 9 août 2018

Conditional check for collections using Java stream

I have the following JSON object. I am trying to validate every field in the object as one or more fields can be null or empty.

{
    "Courses": [
        {
            "CourseName": "Java", 
            "Scores": [
                {
                    "Score1": 10 
                }, 
                {
                    "Score2": 9
                }, 
                {
                    "Score3": 10
                }
            ]
        }, 
        {
            "CourseName": "Biology", 
            "Scores": [
                {
                    "Score1": 8 
                }, 
                {
                    "Score2": 9
                }, 
                {
                    "Score3": 10 
                }
            ]
        }
    ]
}

I am trying to check every field in the object as one or more fields can be null or empty.
I want to return all the fields that failed the check. I'm new to Streams in Java8, and I've come up with this somewhat messy sequence.

public void checkFields(Student student) {
        if(student.getCourses().stream().
                anyMatch(course -> course.getCourseId()== null))
            break;
        else {
            if (student.getCourses().stream().anyMatch(course -> course.getScores() == null))
                break;
            else {
                List<Scores> scoreList = student.getScores();
                if (scoreList.stream().
                        flatMap(l -> l.getScores().stream()).anyMatch(score -> score.getScore() == 0))
                    break;
            }
        }

Can this check process be improved?

Aucun commentaire:

Enregistrer un commentaire