Java中List集合去除重复数据的方法
1. 循环list中的所有元素然后删除重复
1 public static List removeDuplicate(List list) { 2 for ( int i = 0 ; i < list.size() - 1 ; i ++ ) { 3 for ( int j = list.size() - 1 ; j > i; j -- ) { 4 if (list.get(j).equals(list.get(i))) { 5 list.remove(j); 6 } 7 } 8 } 9 return list; 10 }
2. 通过HashSet踢除重复元素
1 public static List removeDuplicate(List list) { 2 HashSet h = new HashSet(list); 3 list.clear(); 4 list.addAll(h); 5 return list; 6 }
3. 删除ArrayList中重复元素,保持顺序
1 // 删除ArrayList中重复元素,保持顺序 2 public static void removeDuplicateWithOrder(List list) { 3 Set set = new HashSet(); 4 List newList = new ArrayList(); 5 for (Iterator iter = list.iterator(); iter.hasNext();) { 6 Object element = iter.next(); 7 if (set.add(element)) 8 newList.add(element); 9 } 10 list.clear(); 11 list.addAll(newList); 12 System.out.println( " remove duplicate " + list); 13 }
4.把list里的对象遍历一遍,用list.contain(),如果不存在就放入到另外一个list集合中
1 public static List removeDuplicate(List list){ 2 List listTemp = new ArrayList(); 3 for(int i=0;i<list.size();i++){ 4 if(!listTemp.contains(list.get(i))){ 5 listTemp.add(list.get(i)); 6 } 7 } 8 return listTemp; 9 }