Intersection of Two Lists Objects in java 8

前端 未结 2 1045
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 08:17

An intersection of Two Lists Objects in java 8. Can some tell me what am I doing wrong?

List originalStudent = new ArrayList<>();
List&l         


        
相关标签:
2条回答
  • 2021-01-06 08:52

    Can some tell me what am I doing wrong?

    You violate the Side-effects principle of java-stream which in a nutshell says that a stream shouldn't modify another collection while performing the actions through the pipelines. I haven't tested your code, however, this is not a way you should treat streams.


    How to do it better?

    Simply use the List::contains in the filter's predicate to get rid of the unique values.

    List<Student> students = originalStudent.stream()
                                            .filter(newStudent::contains)
                                            .collect(Collectors.toList());
    

    This solution (understand the method List::contains) is based on the implemented equality comparison using Object::equals. Hence, there is needed to override the very same method in the class Student.

    Edit: Please, be aware that that automatically overriding the Object::equals will mind the id to the equality computation. Therefore the equality will be based on the name and surname only. (thanks to @nullpointer).

    Without the Object::equals overridden?

    You have to perform the comparison in the filter using another stream and the method Stream::anyMatch which returns true if the predicate is qualified.

    List<Student> students = originalStudent.stream()
                  .filter(os -> newStudent.stream()                    // filter
                      .anyMatch(ns ->                                  // compare both
                           os.getName().equals(ns.getName() &&         // name
                           os.getLastName().equals(ns.getLastName()))) // last name
                  .collect(Collectors.toList());
    
    0 讨论(0)
  • 2021-01-06 09:05

    What you can do is construct a SortedSet<Student> from the two concatenated lists originalStudent and newStudent. The sorted set uses a Comparator.comparing(Student::getName).thenComparing(Student::getLastName) as its comparator.

    Stream.concat(originalStudent.stream(), newStudent.stream())
        .collect(Collectors.toCollection(() -> new TreeSet<>(
            Comparator.comparing(Student::getFname)
                .thenComparing(Student::getLname))
        ))
    
    0 讨论(0)
提交回复
热议问题