How do compare an internal field between two lists in Java?

Viewed 45

I have List<MainClass> list1 and List<MainClass> list2.

public class MainClass {
    private List<Question> questions;
}

public class Question {
    private Long questionId;
}

I need to compare the questionId from the list1 with the questionId from the list2. I should get those questionId (as List<Long> ids) from the List1 which are absent in the List2.

I have written next code where I seperatly where I separately get ids from the list1 and list2. Then I have to compare the idsFromList1 and the idsFromList1 to find out a absent Ids. My question: Is the way to get those questionId (as List ids) from the List1 which are absent in the List2 using stream or in some a short, elegant way?

List<Long> idsFromList1= list1.stream().map(mc->mc.getQuestion)).flatMap(List::stream).map(q->q.getQuestionId()).collect(Collectors.toList());
List<Long> idsFromList2= list2.stream().map(mc->mc.getQuestion)).flatMap(List::stream).map(q->q.getQuestionId()).collect(Collectors.toList());
1 Answers

Yes, it is possible to add a filter() call to a Stream of list1's question IDs, where the predicate would check the elements of list2, and return true if none of them has the current ID.

List<Long> diff = list1.stream()
                       .flatMap(mc->mc.getQuestions().stream()
                                                     .map(Question::getQuestionId))
                       .filter(id1 -> list2.stream()
                                           .flatMap(mc->mc.getQuestions().stream()
                                                                         .map(Question::getQuestionId))
                                           .noneMatch(id2 -> id2.equals(id1)))
                              .collect(Collectors.toList());

However, this would take quadratic time to run.

You'd be better off if you produce two Sets of the question IDs and find the difference:

Set<Long> idsFromList1 = list1.stream()
                              .flatMap(mc->mc.getQuestions().stream().map(Question::getQuestionId))
                              .collect(Collectors.toSet());
Set<Long> idsFromList2= list2.stream() .flatMap(mc->mc.getQuestions().stream().map(Question::getQuestionId))
                              .collect(Collectors.toSet());
Set<Long> diff = idsFromList1.removeAll(idsFromList2);
Related