比较两个列表对象 [英] Compare two list objects

查看:146
本文介绍了比较两个列表对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,如下所示:

I have two list as below:

List<Category> categories;
List<Category> selectedCategories;

和类别模型

(id,catTitle,catId)  

但是我想在以下情况下比较两个列表:

but I want to compare two list when:

selectedCategories:[{id=3, catTitle='first', catId=17},{id=4, catTitle='second', catId=18}]
categories: [{id=null, catTitle='first', catId=17}

并获取{id = 3,catTitle ='first',catId = 17}

and get {id=3,catTitle='first',catId=17}

但是当id为null时,如何将{id = 3,catTitle ='first',catId = 17}作为结果?!!!

but when id is null how to have {id=3,catTitle='first',catId=17} as result?!!!

推荐答案

pubic class Category {
   Integer id;
   int catId;
   String catTitle;
   ..........................

   @Override   
   public boolean equals(Object other) {
       return (other instanceOf Category) && equate((Category) other);
   }  

   private boolean equate(Category other) {
       return other != null &&
           catId == other.catId &&  
           equateIds(id, other.id) && 
           equateTitles (catTitle, other.catTitle);
   } 

   // Ids are considered equal, if equal, or at least one is null
   private static bool equateIds(Integer id1, Integer id2) {
      return (id1==null) || (id2==null) ||
            id1.intValue() == id2.intValue(); 
   } 

   // Titles are considered equal, if equal, or both null
   private static bool equateTitles(String title1, Integer title2) {
      return (title1==null) ? (title2 == null) : title1.equals(title2);
   } 

}

更新:为了保持一致,您还需要hashCode忽略ID:

Update: for consistency you also need hashCode ignoring id:

@Override
public int hashCode() {
    return catId + ((catTitle == null) ? 0 : catTitle.hashCode());
}

要获取通用元素:

List<Category> selectedElements = (new List<Category>(originalList)).retainAll(lookForList);

这篇关于比较两个列表对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆