两个对象list 标识出 对象中相同的 与不同的

private Map<Integer, List<QueryAllLabelsResponse>> findListDiff(List<QueryAllLabelsResponse> rps1, List<QueryAllLabelsResponse> rps2){
    //判断不能为空
    if(rps1 == null || rps1.isEmpty() || rps2 == null || rps1.isEmpty()) return null;
    //保存最后的数据
    Map<Integer, List<QueryAllLabelsResponse>>  mapList = new HashMap<Integer, List<QueryAllLabelsResponse>>(3);

    //复制rps1,作为备份
    List<QueryAllLabelsResponse> rps1_bak = new ArrayList<QueryAllLabelsResponse>(rps1);

    //1、获取rps1中与rps2中不同的元素
    rps1.removeAll(rps2);

    //2、获取rps1和rps2中相同的元素
    rps1_bak.removeAll(rps1);

    //3、获取rps2中与rps1中不同的元素
    rps2.removeAll(rps1_bak);

    //经过此转换后rps1中数据与rps2中的数据完全不同
    //rps1_bak是rps1和rps2的交集
    //rps2中的数据与rps1中的数据完全不同

    mapList.put(0, rps1);//rps1中独有的数据
    mapList.put(1, rps1_bak);//交集的数据
    mapList.put(2, rps2);//rps2中的独有数据


    return mapList;
}


QueryAllLabelsResponse  对象需要重写hashCode与equals  

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    QueryAllLabelsResponse that = (QueryAllLabelsResponse) o;
    return Objects.equals(labelId, that.labelId) &&
            Objects.equals(parentId, that.parentId) &&
            Objects.equals(labelType, that.labelType);
}
只要 这三个参数一样 就认为两个对象为相同的    


猜你喜欢

转载自blog.csdn.net/tanshaonan888/article/details/79911725