List object deduplication case

Deduplication of Merging Multiple Lists (Java)

Scenario: A list collection needs to merge multiple lists, and duplicate elements cannot appear.
Example: Permission business, one account has multiple roles. Each role has different permissions, and there may be duplicate permissions between different roles.

plan :

(1) Code: (high efficiency, use the collection feature to merge and deduplicate in one step)

Set<Object> set = new HashSet(); //合集
List<Object> listA = new ArrayList<>(); //A集合
List<Object> listB = new ArrayList<>(); //B集合
set.addAll(listA);
set.addAll(listB);

(2) Code: (low efficiency, many codes)

A (collection)     B (collection)     C (collection)
first add the elements of the BC collection to the A collection individually, and then judge whether the value is equal to achieve the effect of deduplication (if it is an object type, it will take one more step).


(3) Code: (low efficiency, less code than 2)
use the addAll() method of List, and then deduplicate.


Attachment: Object deduplication requires corresponding deduplication objects to rewrite hashcode() and equals() methods.
Because the equals() method of Object is to compare memory addresses, the memory addresses of two objects are of course not equal, but the values ​​​​of the objects are the same , so we have to rewrite the equals() method, why rewrite hashcode(), although only the equals() method is used here, but when the object uses the Hash-related package, the hashcode() method needs to be used to Judging will result in equal objects but unequal hash codes, so it is stipulated that they must be rewritten together. If the object deduplication does not rewrite the comparison method, it can also be implemented using a comparator: (Example)

Set<Object>  rs = new TreeSet<Object>(new Comparator<Object>() {
    
    
       @Override
       public int compare(Object a1, Object a2) {
    
    
          return a1.getValue().compareTo(a2.getValue());
       }
});
通过比较对象的Value属性来判断是否相等.

You can refer to this article: click me

Attachment 2: Method 2 uses streaming operations

//实体对象
public class AreaInfo{
    
    
	private String provinceCode;
	private String name;
}

List<AreaInfo> list =  new ArrayList<>();
......省略添加重复对象数据代码

//------------------[根据属性(provinceCode)去重]----------------
List<AreaInfo> provinces = list.stream().collect(collectingAndThen(
                    toCollection(() -> new TreeSet<AreaInfo>(
                            comparing(areaInfo->areaInfo.getProvinceCode()))),ArrayList::new));

Friends, if you have new ideas, you can leave a message in the comment area!

Guess you like

Origin blog.csdn.net/AKALXH/article/details/116223946