javajava-streamnosuchelementexception

NoSuchElementException on Stream iterating List<Object>


hi! Try to use this stream, but i got NoSuchElementException on

var scores = findAllByBarcode
                .stream()
                .iterator()
                .next()
                        .getMpProductFeedbacks()
                                .stream()
                                        .filter(mpProductFeedback -> mpProductFeedback.getId()==mpProductFeedbackId)
                                               .iterator()
                .next()
                .getMpPersonScores()
                .stream()
                .map(mpPersonScore -> {
                            var score = new ScoreType();
                            score.setUserScore(mpPersonScore.getMpPersonScore());
                            score.setUser(mpPersonScore.getMpPersonLogin());
                            score.setUserComment(mpPersonScore.getMpPersonComment());
                            return score;
                })
    .toList();

got exception after part

filter(mpProductFeedback -> mpProductFeedback.getId()==mpProductFeedbackId)
                                           .iterator()
            .next()

tried to use orElse, but it works only with .equals i already have == between two longs.


Solution

  • Assuming we're dealing with nested Collections

    List<ScoreType> scores = findAllByBarcode
        .stream()
        .map( b -> b.getMpProductFeedbacks() )
        .flatMap( Collection::stream )
        .filter( feedback -> feedback.getId() == mpProductFeedbackId )
        .map( feedback -> feedBack.getMpPersonScores() )
        .flatMap( Collection::stream )
        .map( personScore -> {
            ScoreType score = new ScoreType();
            score.setUserScore( personScore.getMpPersonScore() );
            score.setUser( personScore.getMpPersonLogin() );         
            score.setUserComment( personScore.getMpPersonComment() );
            return score;
        })
       .toList();