java list 去除 重复值

来源:互联网 发布:亚投行 现状 知乎 编辑:程序博客网 时间:2024/06/05 10:42

一:Hastset根据hashcode判断是否重复,数据不会重复

 Java代码 

  1. /** List order not maintained **/      
  2. public static void removeDuplicate(ArrayList arlList)      
  3. {      
  4. HashSet h = new HashSet(arlList);      
  5. arlList.clear();      
  6. arlList.addAll(h);      
  7. }  

二:通过Hashset的add方法判断是否已经添加过相同的数据,如果已存在相同的数据则不添加

 

Java代码 
  1. /** List order maintained **/      
  2. public static void removeDuplicateWithOrder(ArrayList arlList)      
  3. {      
  4. Set set = new HashSet();      
  5. List newList = new ArrayList();      
  6. for (Iterator iter = arlList.iterator(); iter.hasNext(); )      
  7. {      
  8. Object element = iter.next();      
  9. if (set.add(element)) newList.add(element);      
  10. }      
  11. arlList.clear();      
  12. arlList.addAll(newList);      
  13. }   

以下来自网络:
 

方法一:循环元素删除 

 //  删除ArrayList中重复元素 
 public   static   void  removeDuplicate(List list)  {
   for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {
    for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {
      if  (list.get(j).equals(list.get(i)))  {
        list.remove(j);
      } 
    } 
  } 
  System.out.println(list);
}


方法二:通过HashSet剔除

 //  删除ArrayList中重复元素 
 public   static   void  removeDuplicate(List list)  {
    HashSet h  =   new  HashSet(list);
    list.clear();
    list.addAll(h);
    System.out.println(list);
}


方法三 删除ArrayList中重复元素,保持顺序

 // 删除ArrayList中重复元素,保持顺序 
 public   static   void  removeDuplicateWithOrder(List list)  {
      Set set  =   new  HashSet();
      List newList  =   new  ArrayList();
   for  (Iterator iter  =  list.iterator(); iter.hasNext();)  {
         Object element  =  iter.next();
         if  (set.add(element))
            newList.add(element);
     } 
     list.clear();
     list.addAll(newList);
     System.out.println( " remove duplicate "   +  list);
 }
 
自己使用: 删除 “0.0”的值
List<List<String>> list1 = (List<List<String>>) map.get("商品入库表"); //表1 入库详细表


//删除list中 数量为 0值
for (Iterator<List<String>> item = list1.iterator(); item.hasNext(); ) {
List<String> it = item.next();
System.out.print(it);
if (it.get(4).equals("0.0")) {
item.remove();
}
}
链接地址:http://iteye.blog.163.com/blog/static/186308096201302565345510/


原创粉丝点击