Home >类库下载 >java类库 >java list remove duplicate values

java list remove duplicate values

高洛峰
高洛峰Original
2016-10-09 16:40:191753browse

One:

Hastset determines whether it is duplicated based on hashcode, and the data will not be repeated

Java code

/** List order not maintained **/ ashSet h = new HashSet (arlList);

arlList.clear();

arlList.addAll(h); Then do not add

Java code

/** List order maintained **/      
public static void removeDuplicateWithOrder(ArrayList arlList)      
{      
Set set = new HashSet();      
List newList = new ArrayList();      
for (Iterator iter = arlList.iterator(); iter.hasNext(); )      
{      
Object element = iter.next();      
if (set.add(element)) newList.add(element);      
}      
arlList.clear();      
arlList.addAll(newList);      
}

The following comes from the Internet:

Method 1: Loop element deletion

//  删除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);
}

Method 2: Eliminate through HashSet

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

Method 3: Delete duplicate elements in ArrayList and maintain order

// 删除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();
    }
}

Link address: http://iteye.blog.163.com/blog/static/186308096201302565345510/

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn