`
y806839048
  • 浏览: 1085201 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

list合并

阅读更多
从数据库中查询出记录,然后以对象的形式封装到List中去。此时假设有两个条件A和B,满足A的记录集和为ListA,满足B的记录集合为ListB,现在要将ListA和ListB合并为一个List,注意ListA和ListB中可能有重复的记录(因为可能某条记录即满足条件A又满足条件B),要过滤掉重复的记录。

方法过程:假设List中存放的对象都是Order对象,属性orderId用于标识一个唯一的Order对象
List<order></order> list = new ArrayList<order></order>();   
  
          if(ListA!=null){   
  
            Iterator it= ListA.iterator();   
  
            while(it.hasNext()){   
  
                list.add((Order)it.next());   
  
            }   
  
         }   
  
if(ListB!=null){   
  
            Iterator it= ListB.iterator();   
  
            while(it.hasNext()){   
  
              Order o=(Order)it.next();   
  
              if(list.contains(o))   
  
                  list.add(o);   
  
            }   
  
         }   
  
首先将ListA中的对象全部装入到list中,然后在装入ListB中对象的

          时候对ListB中的每个元素进行一下判断,看list中是否已存在该元素,这里我们使用List接口的contains()方法。它的原理是这样的:如上例中的 list.contains(o),系统会对list中的每个元素e调用o.equals(e),方法,加入list中有n个元素,那么会调用n次o.equals(e),只要有一次o.equals(e)返回了true,那么list.contains(o)返回true,否则返回false。因此为了很好的使用contains()方法,我们需要重新定义下Order类的equals方法,根据我们的业务逻辑,如果两个Order对象的orderId相同,那么我们认为它们代表同一条记录,于是equals方法定义如下:
public boolean equals(Object obj) {   
  
             if (this == obj)   
  
                 return true;   
  
             if (obj == null)   
  
                 return false;   
  
             if (getClass() != obj.getClass())   
  
                 return false;   
  
             final Order other = (Order) obj;   
  
              if(this.getOrderid()!=other.getOrderid())   
  
                 return false;   
  
             return true;   
  
        }   

这样只要ListB中有一条记录的orderId和list中的某条记录的orderId

相等,就认为该记录已存在,不再将它放入list,这样就避免了重复记录的存在。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics