1 Service Scenario

Taking the Olympic Math Class and the English class as an example, there is overlap between the students in these two classes. Now I need to count all the students who participate in extracurricular classes.

The logic is simple, but the actual code can vary, and let’s discuss what I think are the two easiest ways

2 Solution

Suppose we have the following two lists:

List<Student> test1;
List<Student> test2;
Copy the code

2.1 the contains

The contains method in the List can determine if it contains the target object.

test2.forEach(student -> {
    if (!test1.contains(student)) {
        test1.add(student);
    }
})
Copy the code

2.2 the stream

Take advantage of the new Java8 stream feature (which I love, to be honest) for de-duplication

Why stream? Because the contains method of List when the contents of our array are objects

test1.addAll(test2);
result = test1.stream().distinct().collect(Collectors.toList());
Copy the code

Rewrite equals and hashCode

The above two methods need special attention when the contents of the array are objects:

  1. Be sure to override equals using the method in 2.1
  2. Using the 2.2 method, be sure to override equals and hashCode because stream().distinct() will use hashCode first and then call equals if it is true