Siva Sai kiran
Siva Sai kiran

Reputation: 67

How to iterate a list and check for match

I have a object

public class QuestionDetails {

    private List<SubQuestion> subQuestions;
    private Long questionId;
}

and i declared SubQuestion as

public class SubQuestion{

    private List<SubQuestion> childQuestions;
    private Long questionId;

}

i am getting question id from user as "questionId" and QuestionDetails object from DB.

Logic

I want to compare the questionId from user with questionId in subQuestions list to get subQuestions object and if i didn't find any match then i wanna go to childQuestions in the same subQuestions object to see if childQuestions list has any match.How can i do that in java8? Right now what i am doing is ,i am checking all sub questions first and if i didn't find any match then i am looking into all child question. my code is below

Long questionId = dto.getQuestions().get(0).getQuestionId ();
     subQuestion= questionDetails.getSubQuestions().stream()
            .filter(sub -> (new Long(sub.getQuestionId()).equals(new Long(questionId))))
            .findAny() .orElse(questionDetailsDTO.getSubQuestions().stream()
                    .flatMap(sub -> sub.getChildQuestions().stream())
                    .filter(child -> (new Long(child.getQuestionId()).equals(newLong(questionId))))
                    .findFirst()
                    .orElse(null));

Upvotes: 0

Views: 1454

Answers (1)

Holger
Holger

Reputation: 298103

Assuming you want a simplified solution, you can use

long questionId = dto.getQuestions().get(0).getQuestionId();
SubQuestion subQuestion = Stream.concat(
      questionDetails.getSubQuestions().stream(),
      questionDetails.getSubQuestions().stream()
          .flatMap(sub -> sub.getChildQuestions().stream())
    )
    .filter(sub -> sub.getQuestionId() == questionId)
    .findFirst().orElse(null);

Since findFirst() respects the encounter order and streams are lazy, the second stream using flatMap will only be processed when the first stream did not encounter a match.

Using long for the type of questionId ensures that the == operator compares the value rather than object identities, regardless of whether getQuestionId() returns Long or long.

Upvotes: 1

Related Questions