Java中List集合去除重復數據的方法匯總
List集合是一個元素有序(每個元素都有對應的順序索引,第一個元素索引為0)、且可重復的集合。
List集合常用方法List是Collection接口的子接口,擁有Collection所有方法外,還有一些對索引操作的方法。
void add(int index, E element);:將元素element插入到List集合的index處; boolean addAll(int index, Collection<? extends E> c);:將集合c所有的元素都插入到List集合的index起始處; E remove(int index);:移除并返回index處的元素; int indexOf(Object o);:返回對象o在List集合中第一次出現的位置索引; int lastIndexOf(Object o);:返回對象o在List集合中最后一次出現的位置索引; E set(int index, E element);:將index索引處的元素替換為新的element對象,并返回被替換的舊元素; E get(int index);:返回集合index索引處的對象; List<E> subList(int fromIndex, int toIndex);:返回從索引fromIndex(包含)到索引toIndex(不包含)所有元素組成的子集合; void sort(Comparator<? super E> c):根據Comparator參數對List集合元素進行排序; void replaceAll(UnaryOperator<E> operator):根據operator指定的計算規則重新設置集合的所有元素。 ListIterator<E> listIterator();:返回一個ListIterator對象,該接口繼承了Iterator接口,在Iterator接口基礎上增加了以下方法,具有向前迭代功能且可以增加元素: bookean hasPrevious():返回迭代器關聯的集合是否還有上一個元素; E previous();:返回迭代器上一個元素; void add(E e);:在指定位置插入元素;Java List去重1. 循環list中的所有元素然后刪除重復
public static List 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); } } } return list; }
2. 通過HashSet踢除重復元素
public static List removeDuplicate(List list) { HashSet h = new HashSet(list); list.clear(); list.addAll(h); return list; }
3. 刪除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); }
4.把list里的對象遍歷一遍,用list.contain(),如果不存在就放入到另外一個list集合中
public static List removeDuplicate(List list){List listTemp = new ArrayList();for(int i=0;i<list.size();i++){if(!listTemp.contains(list.get(i))){listTemp.add(list.get(i));}}return listTemp;}總結
到此這篇關于Java中List集合去除重復數據方法匯總的文章就介紹到這了,更多相關Java List去除重復內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: