Java中List集合去除重復(fù)數(shù)據(jù)的方法匯總
List集合是一個元素有序(每個元素都有對應(yīng)的順序索引,第一個元素索引為0)、且可重復(fù)的集合。
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集合中第一次出現(xiàn)的位置索引; int lastIndexOf(Object o);:返回對象o在List集合中最后一次出現(xiàn)的位置索引; 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):根據(jù)Comparator參數(shù)對List集合元素進行排序; void replaceAll(UnaryOperator<E> operator):根據(jù)operator指定的計算規(guī)則重新設(shè)置集合的所有元素。 ListIterator<E> listIterator();:返回一個ListIterator對象,該接口繼承了Iterator接口,在Iterator接口基礎(chǔ)上增加了以下方法,具有向前迭代功能且可以增加元素: bookean hasPrevious():返回迭代器關(guān)聯(lián)的集合是否還有上一個元素; E previous();:返回迭代器上一個元素; void add(E e);:在指定位置插入元素;Java List去重1. 循環(huán)list中的所有元素然后刪除重復(fù)
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踢除重復(fù)元素
public static List removeDuplicate(List list) { HashSet h = new HashSet(list); list.clear(); list.addAll(h); return list; }
3. 刪除ArrayList中重復(fù)元素,保持順序
// 刪除ArrayList中重復(fù)元素,保持順序 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;}總結(jié)
到此這篇關(guān)于Java中List集合去除重復(fù)數(shù)據(jù)方法匯總的文章就介紹到這了,更多相關(guān)Java List去除重復(fù)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. html清除浮動的6種方法示例2. JavaScript數(shù)據(jù)類型對函數(shù)式編程的影響示例解析3. 利用CSS3新特性創(chuàng)建透明邊框三角4. 詳解CSS偽元素的妙用單標(biāo)簽之美5. div的offsetLeft與style.left區(qū)別6. CSS代碼檢查工具stylelint的使用方法詳解7. 使用css實現(xiàn)全兼容tooltip提示框8. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)9. vue實現(xiàn)將自己網(wǎng)站(h5鏈接)分享到微信中形成小卡片的超詳細教程10. 不要在HTML中濫用div
