The List element is a class object, and the solution is to deduplicate according to the attributes of the class object

Many small partners will encounter a scenario in development, that is, class objects are stored in the List collection, and we want to deduplicate according to the attributes of the class objects; how to do this scenario?

Solution:

Everyone knows that the equals of an object is compared according to the application address of the object by default, so if you want to deduplicate an object, the key is to rewrite the equals method (if you rewrite equals(), you must also rewrite hashcode())

1. With IDEA, press Alt + Insert in the class to automatically rewrite the equals() and hashCode() methods

My class has only one name attribute, and the rewriting code is as follows:

2. Use the new feature Stream of JDK8 to deduplicate

list.stream().distinct().collect(Collectors.toList());

What you get at this point is the deduplicated list.

Remember, rewriting equals() must rewrite hashcode()! ! !

Guess you like

Origin blog.csdn.net/w20001118/article/details/128723824